1. Basic settings and loading:
Initialization: Declare<WebView>in layout XML or dynamically create it in code (WebView WebView=new WebView (context); ).
Loading content:
LoadURL (String URL): Load the network URL.
LoadData (String data, String mimeType, String encoding): Load an HTML string.
loadDataWithBaseURL(String baseUrl, String data, String mimeType, String encoding, String historyUrl): Load an HTML string and specify the base URL (for parsing relative path resources).
Required permission: INTERNET (load network content). Consider using ACCESS_CETWORK_STATE for network state aware optimization.
Enable JavaScript: webView. getSetts(). setJavaScriptEnabled (true); ( ⚠️ Security risks: need to be handled with caution.
2. WebViewClient: Control page behavior
Handling page navigation, loading events, error handling, etc.
Key callback methods:
Should Override URL Loading (WebView view, Webex Resource Request request): Intercept URL loading and decide whether to handle it with WebView or hand it over to the system/other apps (to implement routing control and deep linking processing).
OnPageStarted (WebView view, String URL, bitmap favicon): The page starts loading.
OnPageFinished (WebView view, String URL): Page loading completed( ⚠️ Not absolutely reliable, there may be asynchronous resource loading).
onReceivedError(WebView view, WebResourceRequest request, WebResourceError error): Loading error (network error, 404, etc.).
OnReceptdHttpError (...): Receive HTTP error status code (such as 500).
OnReceptdSslError (...): SSL certificate error handling( ⚠️ It is strongly not recommended to simply call handler. proseed() to ignore all errors, as there is a risk of man in the middle attacks! Should verify the certificate or prompt the user).
3. WebChrome Client: Handling browser features
Process progress bars, JS dialog boxes (alert, confirm, prompt), console messages, webpage titles/icons, file selections, permission requests (camera, geolocation), etc.
Key callback methods:
OnProgressChanged (WebView view, int newProgress): Update the loading progress bar.
OnReceptdTitle (WebView view, String title): Retrieve the webpage title.
OnJsAlert/Confirm/Prompt (...): Handling JavaScript dialog boxes (must be overridden to display native dialog boxes, otherwise invalid).
onShowFileChooser(...) / onPermissionRequest(...) / onGeolocationPermissionsShowPrompt(...): Handle file selection, permission requests, etc.
4. JavaScript and Native Communication (JSBridge)
Native -> JS: webView.loadUrl("javascript:yourFunctionName('" + arg + "')"); or webView.evaluateJavascript("yourFunctionName('" + arg + "')", new ValueCallback<String>() {...}); (Recommended for the latter, asynchronous and supports return values).
JS -> Native:
AddJavascriptInterface (Object obj, String interacteName): Inject Java objects into JS context, and JS can directly call its @ JavascriptInterface annotation method. ( ⚠️ API Level 17+requires mandatory annotations, low versions pose serious security risks! )
Should OverrideUrlLoading intercept custom schemes (e.g, jsbridge://action?params=value )Resolve URLs and perform corresponding native operations.
OnJsCompt interception: JS passes JSON strings through prompt(), Native parses and executes them, and returns the result. (A commonly used and relatively safe solution).
Safety advice:
Strictly limit the methods of injecting objects and only expose necessary interfaces.
Strictly verify and filter the parameters passed by JS.
Use HTTPS to prevent communication from being eavesdropped/tampered with.
Consider using a mature and security audited JSBridge library.
5. WebView Lifecycle Management
Activity/Fragment Lifecycle Synchronization:
OnPause(): webView. onPause() - Pause processing (JS timer, animation, etc.). If a plugin is used, it may be necessary to call webView. auseTimers().
OnResume(): webView. onResume()/webView. ResumeTimers() - Resume processing.
OnDestroy(): It is necessary to call webView. destroy() to free resources and avoid memory leaks. First, remove the WebView from its parent View (ViewGroup. removeView), and then call WebView. destroy().
1. Optimization of startup speed (reducing white screen time)
Pre create&Warm up:
Create a WebView instance (new WebView (context. getApplianceContext())) in advance in the Application or backend Service, and perform basic initialization (setting UA, enabling JS, etc.). Use the preheated instance directly during the first loading. Pay attention to the use of Application Context.
API Level 29+: Use WebView. setDataLayoutSuffix (String Suffix) and WebView. reload() for safer and more efficient preheating.
Template Preloading: If the app has a fixed WebView skeleton/template (such as a navigation bar), a local HTML template (loadDataWithBaseURL) can be loaded in advance, and the actual content can be injected later through JS.
Data prefetching: Obtain the required network data (API data) in advance before the user may enter the WebView page, and directly render the WebView after loading to reduce waiting.
Parallel loading: Start the initialization process of WebView while Native loads its own resources.
2. Page loading speed optimization
Cache Control:
webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT | LOAD_CACHE_ELSE_NETWORK | LOAD_NO_CACHE | LOAD_CACHE_ONLY); Set according to requirements.
HTTP caching: Utilize WebSettings. setAppCacheEnabled (true) (obsolete but partially valid in older versions) and HTTP standard cache headers (Cache Control, ETag). It is more recommended to rely on HTTP standard caching.
DOM Storage (LocalStorage/SessionStorage): webSettings.setDomStorageEnabled(true);。
IndexedDB: webSettings.setDatabaseEnabled(true); (Usually, the database path webSettings. setDatabasePath (...) needs to be specified, but modern WebViews may automatically manage it).
File system API: webSettings. setAllowFileAccess (true); / webSettings.setAllowContentAccess(true); (Pay attention to safety).
Custom disk cache: Consider managing offline packages (ZIP) yourself and providing local resources by intercepting should InterceptRequest.
Resource interception and replacement (should InterceptRequest):
Intercept specific requests (such as images, CSS, JS) and provide resources from local cache, pre downloaded packages, or CDN.
Replace low resolution images with placeholder or higher definition versions.
Merge small file requests.
CDN acceleration: Ensure that web resources are deployed on high-quality CDN.
Optimizing web content itself: this is the most fundamental! Compress resources (Gzip/Brotli), optimize images (WebP/AVIF), reduce request count (Sprite images, code merging), delay loading, load on demand, optimize JS/CSS execution efficiency. Use Lighthouse/PageSpeed Insights to analyze webpage performance.
Enable hardware acceleration (caution): webView. setLayerType (View.LAYER-TYPE-HARDWARE, null);. Usually, it can improve rendering performance, but it may cause some complex page rendering issues (Invalidation/Overdraw) or memory leaks. Testing is required.
setOffscreenPreRaster (API 24+): webView.setOffscreenPreRaster(true); When WebView is in the background but about to be displayed, rendering its content to an off screen bitmap in advance can result in faster display. Consuming additional memory and computing resources.
3. Memory consumption optimization (preventing OOM and leaks)
Isolated Process:
In AndroidManifest.xml, configure android: process=": webview_decess" for activities that contain WebViews.
Advantages: WebView memory consumption is included in the independent process, greatly reducing the OOM risk of the main process; The crash of an independent process does not affect the main process; Process destruction can completely free up WebView memory.
Disadvantages: Cross process communication overhead; Implement more complex (inter process communication IPC); The overall memory usage of the application may slightly increase.
Timely destruction: Strictly follow the lifecycle and first remove View before webView. destroy() in onDestroy().
Avoid holding WebView references in Application/Static Context for a long time: this can prevent the activity from being reclaimed, resulting in serious leaks.
Monitoring memory: Use Android Profiler (Memory Profiler) to monitor the memory usage of the WebView process, focusing on WebView objects, WebViewCore, BrowserFrame, geolocation, etc.
ClearCache/ClearHistory/ClearFormData: Clear cache, history, and form data in a timely manner to free up memory. ClearCache (true) Clears disk and memory cache.
Be cautious when using hardware acceleration: As mentioned earlier, the hardware acceleration layer (LAYER-TYPE-HARDWARE) occupies more video memory.
4. Rendering performance optimization (smoothness)
setEnableSlowWholeDocumentDraw (API 21+): webView.setEnableSlowWholeDocumentDraw(false); (The default is usually false). Setting it to true will force the entire document to be drawn at once, which may cause lag. Generally, the default value of false is kept.
Optimize web content: reduce complex CSS animations/transformations, avoid forced layout synchronization (offsetHeight reading), use requestAnimationFrame, optimize Canvas drawing, and reduce DOM complexity.
Hardware acceleration: Enabling hardware acceleration can usually improve scrolling and animation smoothness (see previous precautions).
Profile GPU Rendering: Open "Profile GPU Rendering" ->"On screen as bars" in the developer options, observe the frame time in the WebView area, and identify frame drop situations.
5. Network optimization
SetBlockNetworkLoad (cautious): webSettings. setBlockNetworkLoad (true); Block all network requests (only for pure local content loaded by loadData). Usually not recommended.
setLoadsImagesAutomatically: webSettings.setLoadsImagesAutomatically(true/false); Control whether the image is automatically loaded. Text can be loaded first, and images can be loaded when needed by the user.
setMixedContentMode (API 21+): webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_NEVER_ALLOW | ...); Control the strategy for loading HTTP resources on HTTPS pages to ensure security.
DNS Pre Resolution: Web Standard<link rel="dns-refetch" ref="//cdn. example. com">. WebView itself does not directly provide a Native DNS prefetching API.
Use should InterceptRequest for network layer customization, such as using OkHttp instead of the default implementation for better connection pool management, HTTP/2 support, and more flexible caching policies.
6. Security reinforcement
HTTPS: Enforce the use of HTTPS. Do not proceed easily in onReceptdSslError. Consider using certificate fixation.
setSafeBrowsingEnabled (API 26+): webSettings.setSafeBrowsingEnabled(true); Enable Google Safe Browsing protection.
SetAllowFileAccess/setAllowContentAccess: Strictly control file access (setAllowFileAccess (false), setAllowFileAccessFromFileURLs (false), setAllowUniversalAccessFromFileURLs (false)), unless explicitly required.
AddJavascriptInterface Security:
API 17+only: There are serious vulnerabilities in lower versions.
Only inject necessary interfaces: use @ JavascriptInterface annotation.
Parameter verification: Strictly verify all parameters passed by JS.
Avoid exposing sensitive operations: Do not expose interfaces for file system operations, sensitive data access, etc.
Custom Scheme Security: Strictly verify the protocol, hostname, path, and parameters of the custom Scheme in shouldeOverrideURPLoading.
Content Security Policy (CSP): Set strict CSP policies in web content to restrict resource loading sources and execution permissions.
WebView update: Encourage users to update the system and WebView components (via Google Play), or integrate the latest Chromium kernel within the app (such as Tencent X5 kernel).
7. Compatibility and Debugging
Fragmentation handling: Android 4.4 (KitKat) switches from WebKit to Chromium based WebView. There are significant differences in API behavior and CSS/JS support. Need to test different Android versions (especially 4.4 and above).
Manufacturer ROM differences: Huawei, Xiaomi, Samsung and other manufacturers may modify the WebView kernel or default settings. Conduct cloud based testing to cover mainstream models.
Remote debugging (Chrome VNet):
Enable debugging in WebView code: if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { WebView.setWebContentsDebuggingEnabled(true); }
Connect the phone to the computer via USB and open the Chrome browser to access it chrome://inspect Find your WebView for debugging (similar to debugging Chrome web pages).
Log: Capture JS console. log and other information through WebChromeClient. onConsole Message.
8. Advanced Techniques and Libraries
WebView Pool: For scenarios where WebView is frequently opened and closed, create a WebView object pool reuse instance to avoid the overhead of duplicate creation and destruction.
Third party kernel: Consider using alternative solutions such as Tencent X5 kernel to solve system WebView compatibility issues, provide enhanced features (better video support, file upload, more unified behavior), and better optimizations (such as memory management).
ProGuard/R8: Ensure proper configuration of obfuscation rules and preserve @ JavascriptInterface methods and WebView related classes.
Jetpack Compose: Integrate WebView into the Compose application using AndroidView (factory={context ->WebView (context)}).








