Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 瀏覽器開發實戰:三種常見呼叫場景

編輯:關於 Android 程式設計

在 App 裡開啟網頁是很普遍的行為。本文整理三種最常見的實作方式:喚起系統預設瀏覽器、指定特定瀏覽器開啟,以及載入本機的 HTML 檔案。

一、喚起系統預設瀏覽器

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

這樣 Android 就會自動挑選使用者設定的預設瀏覽器來開啟該網址。

二、指定特定瀏覽器開啟

1. 明確指定系統內建瀏覽器

關鍵在於 setClassName():套件名稱為 com.android.browser,啟動的 Activity 為 com.android.browser.BrowserActivity。

Intent intent = new Intent();
intent.setAction("android.intent.action.VIEW");
Uri content_url = Uri.parse("https://www.jizhuomi.com/android");
intent.setData(content_url);
intent.setClassName("com.android.browser", "com.android.browser.BrowserActivity");
startActivity(intent);

2. 喚起其他第三方瀏覽器

只要把套件名與主 Activity 換掉即可,前提是該瀏覽器已安裝在裝置上:

intent.setClassName("套件名稱", "主啟動 Activity");
  • UC 瀏覽器:com.uc.browser / com.uc.browser.ActivityUpdate
  • Opera:com.opera.mini.android / com.opera.mini.android.Browser
  • QQ 瀏覽器:com.tencent.mtt / com.tencent.mtt.MainActivity

三、開啟本機 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。

為什麼不能用 file:// ?

有 Win32 開發經驗的人可能會想用 file://sdcard/help.html。可以確定的是,預設瀏覽器並未針對 file 這個 scheme 做解析。若要讓系統瀏覽器支援,得自行修改原始碼重新編譯:

  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 形式。

以上三種寫法涵蓋了日常開發中絕大多數「開網頁」的需求。實作時別忘了在需要存讀外部儲存空間的情境下補上相應的執行期權限請求。

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