Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Android Webview and analyze the problems encountered

2025-04-07 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

In this issue, the editor will bring you an analysis of how to use Android Webview and the problems encountered. The article is rich in content and analyzes and narrates it from a professional point of view. I hope you can get something after reading this article.

Text

WebView is a View used to display web pages. It uses the WebKit rendering engine to display web pages, which can load online or local html pages. WebView can perform a series of operations on pages, such as forward and backward history pages, zooming in and out, performing text search, interacting with JS, and so on.

When using Webview, remember to declare INTERNET permissions in the AndroidManifest.xml file:

By default, errors that WebView does not support JavaScript,web pages will also be ignored. If you only use Webview to display web pages without interaction, the default configuration is fine. If you need to interact, you need to customize the configuration.

WebView initializes and loads URL

1. Initialize via XML:

Or directly New:

WebView webview = new WebView (this)

2. Load URL:

WebView myWebView = (WebView) findViewById (R.id.webview); myWebView.loadUrl ("http://www.example.com");"

Or you can load Html directly:

String summary = "You scored 192 points."; myWebView.loadData (summary, "text/html", null)

If you want to add Header information when loading URL, you can override the loadUrl () method, such as:

@ Override public void loadUrl (String url) {Map map = new HashMap (); map.put ("ajax", "true"); map.put ("appversion", SharedPreferencesUtil.getAppVersion (getContext ()); map.put ("clientid", SharedPreferencesUtil.getClientId (getContext (); loadUrl (url, map);}

WebSettings

WebView can be configured in WebSettings through a series of configurations, such as:

WebSettings settings = getSettings (); / / default is false setting true to allow interaction with js settings.setJavaScriptEnabled (true) / / WebSettings.LOAD_DEFAULT if the local cache is available and does not expire, use the local cache. No load the network data default value / / WebSettings.LOAD_CACHE_ELSE_NETWORK load the local cache data first, regardless of whether the cache expires / / WebSettings.LOAD_NO_CACHE only loads the network data, does not load the local cache / / WebSettings.LOAD_CACHE_ONLY only loads the cache data Do not load network data / / Tips: you can use LOAD_DEFAULT when there is a network and LOAD_CACHE_ELSE_NETWORK settings.setCacheMode (WebSettings.LOAD_CACHE_ELSE_NETWORK) when there is no network. / enable DOM storage API with large storage space and use simple settings.setDomStorageEnabled (true); / / set database cache paths to store and manage complex data to facilitate the addition, deletion, modification and query of data. Settings.setDatabaseEnabled (true) is not recommended; final String dbPath = context.getApplicationContext (). GetDir ("db", Context.MODE_PRIVATE). GetPath (); settings.setDatabasePath (dbPath) / / enabling the Application Caches function to facilitate the construction of offline APP is not recommended to use settings.setAppCacheEnabled (true); final String cachePath = context.getApplicationContext (). GetDir ("cache", Context.MODE_PRIVATE). GetPath (); settings.setAppCachePath (cachePath); settings.setAppCacheMaxSize (5 * 1024 * 1024)

Several cache comparisons that can be set in Webview:

WebviewClient

Common methods of WebCromeClient:

1. ShouldOverrideUrlLoading (WebView view, String url)

Out of date after API 24, when a url is about to be loaded by webview, give Application a chance to take over and process the url. The method returns true to handle url; on behalf of Application itself, and returns false to process url on behalf of Webview.

For example, the project needs to deal with whether the passed URL is an event or a HTTP link, which can be filtered by customizing the protocol header (nativeapi://), such as:

@ Override public boolean shouldOverrideUrlLoading (WebView view, String url) {Uri uri = Uri.parse (url); String scheme = uri.getScheme (); if (TextUtils.isEmpty (scheme)) return true; if (scheme.equals ("nativeapi")) {/ / if nativeapi://showImg is used to view large images, the logic return true is added here. } else if (scheme.equals ("http") | | scheme.equals ("https")) {/ / process http protocol if (Uri.parse (url). GetHost (). Equals ("www.example.com")) {/ / Internal URL, do not block, load return false with your own webview } else {/ / Jump external browser Intent intent = new Intent (Intent.ACTION_VIEW, uri); context.startActivity (intent); return true;}} return super.shouldOverrideUrlLoading (view, url);}

Note: if the Post request method is used, this method will not be called back

2. ShouldOverrideUrlLoading (WebView view, WebResourceRequest request)

Added after API 24, use the same as above.

3. ShouldInterceptRequest (WebView view, String url)

After API 21 becomes obsolete, notify Application of the request to load the resource and return the requested resource. If the return value is Null,Webview, the resource will still be loaded normally; otherwise, the returned data will be used.

Note: the callback occurs in the child thread and cannot perform UI operations directly.

4. ShouldInterceptRequest (WebView view, WebResourceRequest request)

Added after API 21, use the same as above.

5. OnPageStarted (WebView view, String url, Bitmap favicon)

Notifies Application that the page has started loading resources, and that onPageStarted will be executed at most once during the page loading process.

6. OnPageFinished (WebView view, String url)

Notify that the Application page has been loaded.

7. OnReceivedError (WebView view, int errorCode, String description, String failingUrl)

Notify Application that errors have occurred and that they are unrecoverable (that is, the main resources are not available). The errorCode parameter corresponds to an ERROR_ * constant

WebCromeClient

1. OnProgressChanged (WebView view, int newProgress)

Notify the loading progress of Application. The value range of newProgress is [0100]. You can use this method to write a Webview with a loading progress bar. For specific examples, please refer to Android to write a Webview with a progress bar.

2. OnReceivedTitle (WebView view, String title)

When there is a change in the title of the loaded page, it will notify Application,title that the new title is.

Control Webview to load history web pages

When WebView overrides URL loading, it automatically accumulates the history of visiting web pages. You can use backward goBack () and forward goForward ().

For example, you can control the back key in Activity to go back to the previous page:

@ Override public boolean onKeyDown (int keyCode, KeyEvent event) {/ / Check if the key event was the Back button and if there's history if ((keyCode = = KeyEvent.KEYCODE_BACK) & & webview.canGoBack ()) {webview.goBack (); return true } / / If it wasn't the Back key or there's no web page history, bubble up to the default / / system behavior (probably exit the activity) return super.onKeyDown (keyCode, event);}

Interaction between Webview and Js

1. Js calls the API Android:

Public class WebAppInterface {Context mContext; / * * Instantiate the interface and set the context * / WebAppInterface (Context c) {mContext = c;} / * * Show a toast from the web page * / @ JavascriptInterface public void showToast (String toast) {Toast.makeText (mContext, toast, Toast.LENGTH_SHORT). Show ();}}

SDK > = 17 (Android4.2) or above, you must add @ JavascriptInterface declaration, and then make it available for Js to call through addJavascriptInterface (), such as:

WebView.addJavascriptInterface (new WebAppInterface (this), "android")

With the above configuration, you can call from Js:

Function showAndroidToast (toast) {/ / call the showToast method Android.showToast (toast) in Android;}

2. Android calls the API of Js:

You can load the Js API through webview.loadUrl ("_ javascript:JsMethod ()"). If you have any parameters, you can add them directly to JsMethod (). The following two methods are encapsulated, namely, loading Js functions with and without parameters:

/ * load JS function with parameters * * @ param JsName JS function name * @ param params variable parameter * / public void loadJSWithParam (String JsName, String... Params) {String TotalParam = ""; for (int I = 0; I

< params.length; i++) { if (i == params.length - 1) { //***一个 TotalParam += (params[i]); } else { TotalParam += (params[i] + "','"); } } this.loadUrl("_javascript:" + JsName + "('" + TotalParam + "')"); } /** * 加载不带参数的JS函数 * * @param JsName JS函数名 */ public void loadJS(String JsName) { this.loadUrl("_javascript:" + JsName + "()"); } Webview的一些优化和遇到的坑 1、Webview打开一个链接,播放一段音乐,退出Activity时音乐还在后台播放,可以通过在Activity的onPause中调用webview.onPause()解决,并在Activity的onResume中调用webview.onResume()恢复,如下: @Override protected void onPause() { h6_webview.onPause(); h6_webview.pauseTimers(); super.onPause(); } @Override protected void onResume() { h6_webview.onResume(); h6_webview.resumeTimers(); super.onResume(); } Webview的onPause()方法官网是这么解释的: Does a best-effort attempt to pause any processing that can be paused safely, such as animations and geolocation. Note that this call does not pause JavaScript. To pause JavaScript globally, use pauseTimers(). To resume WebView, call onResume(). 通知内核尝试停止所有处理,如动画和地理位置,但是不能停止Js,如果想全局停止Js,可以调用pauseTimers()全局停止Js,调用onResume()恢复。 2、5.0 以后的WebView加载的链接为Https开头,但是链接里面的内容,比如图片为Http链接,这时候,图片就会加载不出来,解决方法: if (Build.VERSION.SDK_INT >

= Build.VERSION_CODES.LOLLIPOP) {webSetting.setMixedContentMode (webSetting.getMixedContentMode ());}

The reason is that the mixed mode of Https and Http is not supported after 5.0. for more information, please see the mixed problem of Http and Https in Android5.0 WebView.

3. When WebView and JavaScript call each other, if there is no configuration confusion in debug, the call will be fine, but when the configuration is confused, it will not be called normally, so the solution:

Configure in the proguard-rules.pro file:

-keepattributes * Annotation*-keepattributes * JavascriptInterface*-keep public class org.mq.study.webview.DemoJavaScriptInterface {public;}

If it is an inner class:

-keepattributes * Annotation*-keepattributes * JavascriptInterface*-keep public class org.mq.study.webview.webview.DemoJavaScriptInterface$InnerClass {public;} the above is the analysis of how to use Android Webview and the problems encountered. If you happen to have similar doubts, please refer to the above analysis. If you want to know more about it, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report