Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android 中調用瀏覽器的幾種方式

編輯:Android 開發實例

在 App 裡開網頁是很常見的需求,Android 提供了幾種不同的調用方式,各有適用情境。

一、交給系統預設瀏覽器

Intent intent = new Intent();
intent.setAction("android.intent.action.VIEW");
Uri content_url = Uri.parse("https://www.example.com");
intent.setData(content_url);
startActivity(intent);

這樣 Android 就會喚起手機的預設瀏覽器前往該網址。最簡單,也最通用。

二、指定特定瀏覽器

如果你希望明確指定用哪一個瀏覽器開啟,只要補上 setClassName(),把套件名稱與啟動 Activity 一起寫死:

intent.setClassName("com.android.browser", "com.android.browser.BrowserActivity");
startActivity(intent);

常見的幾組對應如下(前提是該瀏覽器已安裝在機器上):

  • Android 自帶瀏覽器:com.android.browser / com.android.browser.BrowserActivity
  • UC 瀏覽器:com.uc.browser / com.uc.browser.ActivityUpdate
  • Opera Mini:com.opera.mini.android / com.opera.mini.android.Browser
  • QQ 瀏覽器:com.tencent.mtt / com.tencent.mtt.MainActivity

三、開啟本機 HTML 檔

要開啟裝置上的本機 HTML 檔,一定要明確指定瀏覽器,不能靠方式一那種「交給系統挑」的寫法:

Intent intent = new Intent();
intent.setAction("android.intent.action.VIEW");
Uri content_url = Uri.parse("content://com.android.htmlfileprovider/sdcard/help.html");
intent.setData(content_url);
intent.setClassName("com.android.browser", "com.android.browser.BrowserActivity");
startActivity(intent);

關鍵在於使用了 content 這個 scheme,透過 com.android.htmlfileprovider 來提供檔案。

為什麼不能用 file:// ?

有 Win32 開發經驗的人可能會想:直接寫成 file:///sdcard/help.html 不行嗎?答案是預設瀏覽器並未針對 file 這個 scheme 做解析。若你希望自帶瀏覽器支援它,就得動手改 Android 原始碼。

步驟大致如下:

  1. 開啟 packages/apps/Browser/AndroidManifest.xml,在對應的 <intent-filter> 後補上 file scheme:
<intent-filter>
    <action android:name="android.intent.action.VIEW" />
    <category android:name="android.intent.category.DEFAULT" />
    <category android:name="android.intent.category.BROWSABLE" />
    <data android:scheme="file" />
</intent-filter>
  1. 重新編譯打包、安裝,新的瀏覽器就會認得 file 這個形式。

一般應用開發當然不必走到改原始碼這一步,但理解 intent-filter 與 scheme 的運作,對後續處理各種 URI 會很有幫助。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved