0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

WebViewから地図アプリを開く方法

0
Posted at

WebViewを利用していたアプリでGoogleマップの「アプリで開く」ボタンを押した起きに、正常にマップアプリが起動しない不具合が起きました。調べてみるとマップURLをWebViewで開いた場合、そのままWebページが表示されたり、アプリ起動がうまく動作しないことがあるようです。
ブラウザのデフォルト動作に頼らず明示的に処理する方法をメモします。

override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean {
    val url = request.url.toString()

    if (url.contains("google.com/maps")) {
        val intent = Intent(
            Intent.ACTION_VIEW,
            url.toUri()
        )

        view.context.startActivity(intent)
        return true
    }

    view.loadUrl(url)
    return true
}

これでMapアプリを開くことができます。Intent.ACTION_VIEWを使用しており、Google Mapsのパッケージ名を指定していません。するとAndroidがそのURLを処理できるアプリを探してくれます。実際のコードでは処理できるアプリが見つからない場合もあるので、try/catchでエラーハンドリングします。

もしGoogle Mapsアプリ指定する場合はintentに設定します。

intent.setPackage("com.google.android.apps.maps")
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?