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

用 Intent 在 Android 瀏覽器中開啟網頁

編輯:進階開發

要在應用程式裡把使用者帶到瀏覽器,最乾淨的做法是發出一個 ACTION_VIEW 意圖,把網址交給系統處理。若想明確指定由標準瀏覽器接手,可以再加上元件名稱。

一、開啟線上網頁

Intent it = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.baidu.com"));
it.setClassName("com.android.browser", "com.android.browser.BrowserActivity");
getContext().startActivity(it);

二、開啟本機網頁

要開啟裝置上的 HTML 檔,得透過 Android 內建的 htmlfileprovider 來取得一個 content:// URI,並指明要存在哪裡。

Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);

Uri uri = Uri.parse("content://com.android.htmlfileprovider/sdcard/123.html");
intent.setData(uri);
intent.setClassName("com.android.browser", "com.android.browser.BrowserActivity");

startActivity(intent);

兩段程式碼的差異只在 URI 的來源。第一種寫法的好處是彈性大——如果使用者把預設瀏覽器換成 Chrome、Firefox 或其他 App,系統會依他的設定分派,不需要你猜對方的套件名稱。反過來,若你確實需要指定某個瀏覽器(例如為了測試特定引擎的行為),再用 setClassName 鎖定;此時最好包一層 try-catch,因為在沒有安裝該瀏覽器的裝置上會直接拋出 ActivityNotFoundException。

另外別忘了,存取 /sdcard 需要 READ_EXTERNAL_STORAGE 權限,而較新的 Android 版本還要求執行期動態申請;htmlfileprovider 這條路徑屬於早期寫法,在現代版本上未必可用,新專案建議改用 FileProvider 產生 content URI,並記得在 Intent 上加 FLAG_GRANT_READ_URI_PERMISSION。

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