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?

AndroidでWebページを開く方法

0
Posted at

Webページを開く方法で以下の4つのやり方をメモします。

  • WebViewでアプリ内表示する
  • 外部ブラウザで開く
  • ChromeやFirefoxなど特定のブラウザで開く
  • ブラウザ選択画面を表示する

WebViewでアプリ内表示する

アプリ内でWebページを表示したい場合はWebViewを使用します。

binding.webView.apply {
    webViewClient = WebViewClient()
    settings.javaScriptEnabled = true
    loadUrl("https://example.com")
}

アプリから離脱しないのでログイン状態など管理しやすいです。

外部ブラウザで開く

val intent = Intent(Intent.ACTION_VIEW).apply {
    data = Uri.parse("https://example.com")
}

startActivity(intent)

これはユーザーがデフォルトブラウザに設定しているアプリが起動します。実装が非常に簡単ですが、Webでの処理が終わったらアプリへ戻る必要があります。

特定のブラウザで開く

開きたいブラウザアプリのpackageを指定します。

val url = Uri.parse("https://example.com")

val intent = Intent(Intent.ACTION_VIEW, url).apply {
    `package` = "org.mozilla.firefox" // Firefoxで開く
}

try {
    startActivity(intent)
} catch (e: ActivityNotFoundException) {
    startActivity(Intent(Intent.ACTION_VIEW, url))
}

上記はFirefoxが存在しなければ、ユーザーのデフォルトブラウザで開きます。基本おすすめしない実装ですが、遷移先のWebページで複雑な処理を行っていて特定のブラウザでしか動作を保証できない場合などに使用します。

ブラウザ選択画面を表示する

毎回ユーザーにブラウザを選択してもらうこともできます。
Chrome、Firefox、Edge、Braveなど、インストール済みのブラウザ一覧が表示されます。

val intent = Intent(Intent.ACTION_VIEW, Uri.parse("https://example.com"))

startActivity(
    Intent.createChooser(intent, "ブラウザを選択")
)
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?