Android 提供多種 API,可協助您管理在應用程式中顯示網路內容的 WebView
物件。
本頁面將說明如何使用這些 API,以更有效的方式與 WebView
物件搭配使用,提升應用程式的穩定性和安全性。
版本 API
從 Android 7.0 (API 級別 24) 開始,使用者可以選擇使用數種不同的套件在 WebView
物件中顯示網路內容。AndroidX.webkit 程式庫包含 getCurrentWebViewPackage()
方法,可擷取在應用程式中顯示網頁內容的套件相關資訊。只有在應用程式嘗試使用特定套件的 WebView
實作方式顯示網頁內容時,這個方法才非常實用。
如要使用這個方法,請新增以下程式碼片段中顯示的邏輯:
Kotlin
val webViewPackageInfo = WebViewCompat.getCurrentWebViewPackage(appContext) Log.d("MY_APP_TAG", "WebView version: ${webViewPackageInfo.versionName}")
Java
PackageInfo webViewPackageInfo = WebViewCompat.getCurrentWebViewPackage(appContext); Log.d("MY_APP_TAG", "WebView version: " + webViewPackageInfo.versionName);
Google 安全瀏覽服務
為了讓使用者享有更安全的瀏覽體驗,WebView
物件會使用 Google 安全瀏覽功能驗證網址,這樣您的應用程式在使用者嘗試前往可能不安全的網站時,會顯示警告。
雖然 EnableSafeBrowsing
的預設值是 true,但在某些情況下,您可能只想依條件啟用安全瀏覽功能或停用這項功能。Android 8.0 (API 級別 26) 以上版本支援使用 setSafeBrowsingEnabled()
切換個別 WebView
物件的安全瀏覽功能。
如果想讓所有 WebView
物件都停用安全瀏覽檢查功能,請在應用程式的資訊清單檔案中加入下列 <meta-data>
元素:
<manifest> <application> <meta-data android:name="android.webkit.WebView.EnableSafeBrowsing" android:value="false" /> ... </application> </manifest>
定義程式輔助動作
當 WebView
執行個體嘗試載入由 Google 歸類為已知威脅的頁面時,WebView
預設會顯示插頁式警告,提醒使用者註意已知的威脅。這個畫面可讓使用者選擇仍要載入網址,或返回之前安全無虞的上一頁。
如果您指定 Android 8.1 (API 級別 27) 以上版本,可以透過下列方式定義應用程式如何回應已知威脅:
- 您可以控管應用程式是否要向安全瀏覽服務回報已知威脅。
- 您可以讓應用程式在每次遇到歸類為已知威脅的網址時,自動執行特定動作 (例如返回安全性)。
下列程式碼片段說明如何指示應用程式的 WebView
例項,在遇到已知威脅後一律恢復安全:
Kotlin
private lateinit var superSafeWebView: WebView private var safeBrowsingIsInitialized: Boolean = false // ... override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) superSafeWebView = WebView(this) superSafeWebView.webViewClient = MyWebViewClient() safeBrowsingIsInitialized = false if (WebViewFeature.isFeatureSupported(WebViewFeature.START_SAFE_BROWSING)) { WebViewCompat.startSafeBrowsing(this, ValueCallback<Boolean> { success -> safeBrowsingIsInitialized = true if (!success) { Log.e("MY_APP_TAG", "Unable to initialize Safe Browsing!") } }) } }
Java
private WebView superSafeWebView; private boolean safeBrowsingIsInitialized; // ... @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); superSafeWebView = new WebView(this); superSafeWebView.setWebViewClient(new MyWebViewClient()); safeBrowsingIsInitialized = false; if (WebViewFeature.isFeatureSupported(WebViewFeature.START_SAFE_BROWSING)) { WebViewCompat.startSafeBrowsing(this, new ValueCallback<Boolean>() { @Override public void onReceiveValue(Boolean success) { safeBrowsingIsInitialized = true; if (!success) { Log.e("MY_APP_TAG", "Unable to initialize Safe Browsing!"); } } }); } }
Kotlin
class MyWebViewClient : WebViewClientCompat() { // Automatically go "back to safety" when attempting to load a website that // Google identifies as a known threat. An instance of WebView calls this // method only after Safe Browsing is initialized, so there's no conditional // logic needed here. override fun onSafeBrowsingHit( view: WebView, request: WebResourceRequest, threatType: Int, callback: SafeBrowsingResponseCompat ) { // The "true" argument indicates that your app reports incidents like // this one to Safe Browsing. if (WebViewFeature.isFeatureSupported(WebViewFeature.SAFE_BROWSING_RESPONSE_BACK_TO_SAFETY)) { callback.backToSafety(true) Toast.makeText(view.context, "Unsafe web page blocked.", Toast.LENGTH_LONG).show() } } }
Java
public class MyWebViewClient extends WebViewClientCompat { // Automatically go "back to safety" when attempting to load a website that // Google identifies as a known threat. An instance of WebView calls this // method only after Safe Browsing is initialized, so there's no conditional // logic needed here. @Override public void onSafeBrowsingHit(WebView view, WebResourceRequest request, int threatType, SafeBrowsingResponseCompat callback) { // The "true" argument indicates that your app reports incidents like // this one to Safe Browsing. if (WebViewFeature.isFeatureSupported(WebViewFeature.SAFE_BROWSING_RESPONSE_BACK_TO_SAFETY)) { callback.backToSafety(true); Toast.makeText(view.getContext(), "Unsafe web page blocked.", Toast.LENGTH_LONG).show(); } } }
HTML5 地理位置 API
針對指定 Android 6.0 (API 級別 23) 以上版本為目標的應用程式,Geolocation API 僅適用於安全來源,例如 HTTPS。系統會自動拒絕所有針對不安全來源提出的 Geolocation API 要求,也不會叫用對應的 onGeolocationPermissionsShowPrompt()
方法。
停用指標收集功能
當使用者提供同意聲明時,WebView
可以將匿名診斷資料上傳至 Google。系統會針對將 WebView
執行個體化的各個應用程式,分別收集資料。如要選擇不採用這項功能,您可以在資訊清單的 <application>
元素中建立下列標記:
<manifest> <application> ... <meta-data android:name="android.webkit.WebView.MetricsOptOut" android:value="true" /> </application> </manifest>
只有在使用者「同意」的情況下,應用程式才會上傳資料。想進一步瞭解如何停用診斷資料報告,請參閱「WebView 報表中的使用者隱私權」一文。
終止處理 API
終止處理 API 會處理 WebView
物件的轉譯器程序消失的情況,這些情況可能是因系統終止轉譯器來收回必要記憶體,或轉譯器程序異常終止的情形。透過這個 API,即使轉譯器程序關閉,應用程式仍可繼續執行。
如果轉譯器在載入特定網頁時異常終止,嘗試再次載入同一個網頁,可能會導致新的 WebView
物件表現相同的轉譯異常終止行為。
下列程式碼片段說明如何在 Activity
中使用這個 API:
Kotlin
inner class MyRendererTrackingWebViewClient : WebViewClient() { private var mWebView: WebView? = null override fun onRenderProcessGone(view: WebView, detail: RenderProcessGoneDetail): Boolean { if (!detail.didCrash()) { // Renderer is killed because the system ran out of memory. The app // can recover gracefully by creating a new WebView instance in the // foreground. Log.e("MY_APP_TAG", ("System killed the WebView rendering process " + "to reclaim memory. Recreating...")) mWebView?.also { webView -> val webViewContainer: ViewGroup = findViewById(R.id.my_web_view_container) webViewContainer.removeView(webView) webView.destroy() mWebView = null } // By this point, the instance variable "mWebView" is guaranteed to // be null, so it's safe to reinitialize it. return true // The app continues executing. } // Renderer crashes because of an internal error, such as a memory // access violation. Log.e("MY_APP_TAG", "The WebView rendering process crashed!") // In this example, the app itself crashes after detecting that the // renderer crashed. If you handle the crash more gracefully and let // your app continue executing, you must destroy the current WebView // instance, specify logic for how the app continues executing, and // return "true" instead. return false } }
Java
public class MyRendererTrackingWebViewClient extends WebViewClient { private WebView mWebView; @Override public boolean onRenderProcessGone(WebView view, RenderProcessGoneDetail detail) { if (!detail.didCrash()) { // Renderer is killed because the system ran out of memory. The app // can recover gracefully by creating a new WebView instance in the // foreground. Log.e("MY_APP_TAG", "System killed the WebView rendering process " + "to reclaim memory. Recreating..."); if (mWebView != null) { ViewGroup webViewContainer = (ViewGroup) findViewById(R.id.my_web_view_container); webViewContainer.removeView(mWebView); mWebView.destroy(); mWebView = null; } // By this point, the instance variable "mWebView" is guaranteed to // be null, so it's safe to reinitialize it. return true; // The app continues executing. } // Renderer crashes because of an internal error, such as a memory // access violation. Log.e("MY_APP_TAG", "The WebView rendering process crashed!"); // In this example, the app itself crashes after detecting that the // renderer crashed. If you handle the crash more gracefully and let // your app continue executing, you must destroy the current WebView // instance, specify logic for how the app continues executing, and // return "true" instead. return false; } }
Renderer Importance API
當 WebView
物件以多程序模式運作時,應用程式處理記憶體不足情況的方式會有一定的彈性。您可以使用 Android 8.0 中推出的 Renderer Importance API,為指派給特定 WebView
物件的轉譯器設定優先順序政策。具體來說,您可能希望應用程式的主要部分在顯示應用程式 WebView
物件的轉譯器終止時繼續執行。舉例來說,如果您預期長時間不要顯示 WebView
物件,讓系統收回轉譯器使用的記憶體,就可以採取這種做法。
下列程式碼片段說明如何指派優先順序至與應用程式 WebView
物件相關聯的轉譯器程序:
Kotlin
val myWebView: WebView = ... myWebView.setRendererPriorityPolicy(RENDERER_PRIORITY_BOUND, true)
Java
WebView myWebView; myWebView.setRendererPriorityPolicy(RENDERER_PRIORITY_BOUND, true);
在這個特定程式碼片段中,轉譯器的優先順序會與應用程式的預設優先順序相同,或受限制。當相關的 WebView
物件不再顯示時,true
引數會將轉譯器的優先順序降低為 RENDERER_PRIORITY_WAIVED
。換句話說,true
引數表示應用程式不會考慮系統是否讓轉譯器程序保持運作。事實上,此優先順序較低的等級,很可能在記憶體不足的情況下終止轉譯器程序。
如要進一步瞭解系統如何處理記憶體不足的情況,請參閱「程序和應用程式生命週期」。