在瀏覽器中開啟 URL

使用預設瀏覽器開啟

此示例顯示如何在內建 Web 瀏覽器中而不是在應用程式中以程式設計方式開啟 URL。這樣,你的應用就可以開啟網頁,而無需在清單檔案中包含 INTERNET 許可權。

public void onBrowseClick(View v) {
    String url = "http://www.google.com";
    Uri uri = Uri.parse(url);
    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
    // Verify that the intent will resolve to an activity
    if (intent.resolveActivity(getPackageManager()) != null) {
        // Here we use an intent without a Chooser unlike the next example
        startActivity(intent);
    } 
}

提示使用者選擇瀏覽器

請注意,此示例使用 Intent.createChooser() 方法:

public void onBrowseClick(View v) {
    String url = "http://www.google.com";
    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
    // Note the Chooser below. If no applications match, 
    // Android displays a system message.So here there is no need for try-catch.
    startActivity(Intent.createChooser(intent, "Browse with"));
   
}

在某些情況下,URL 可以以 www 開頭。如果是這種情況,你將獲得此異常:

android.content.ActivityNotFoundException:找不到處理 Intent 的 Activity

該 URL 必須始終以 “http://”“https://” 開頭。因此,你的程式碼應該檢查它,如下面的程式碼片段所示:

if (!url.startsWith("https://") && !url.startsWith("http://")){
    url = "http://" + url;
}
Intent openUrlIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
if (openUrlIntent.resolveActivity(getPackageManager()) != null) {
    startActivity(openUrlIntent);
} 

最佳實踐

檢查裝置上是否有可以接收隱式意圖的應用程式。否則,你的應用會在呼叫 startActivity() 時崩潰。要首先驗證應用程式是否存在以接收意圖,請在 Intent 物件上呼叫 resolveActivity()。如果結果為非 null,則至少有一個應用程式可以處理意圖,並且可以安全地呼叫 startActivity()。如果結果為 null,則不應使用 intent,如果可能,應禁用呼叫 intent 的功能。