当前位置:网站首页>WebView details
WebView details
2022-07-28 12:07:00 【sdfdagdsfgsdg】
- WebView Load web page
mWebView.loadUrl("http://www.baidu.com");
// Load local assets Web pages under the directory
mWebView.loadUrl("file:///android_asset/demo.html");- WebView Basic settings
WebSettings settings = mWebView.getSettings();
settings.setBuiltInZoomControls(true);// Show zoom button (wap Web pages don't support )
settings.setUseWideViewPort(true);// Double click zoom is supported (wap Web pages don't support )
settings.setJavaScriptEnabled(true);// Support js function - Set up WebViewClient
mWebView.setWebViewClient(new WebViewClient() {
// Start loading web page
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
System.out.println(" Start loading web pages ");
}
// End of page loading
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
System.out.println(" End of page loading ");
}
// All links jump to this method
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
System.out.println(" Jump Links :" + url);
view.loadUrl(url);// When jumping links, force the current webview Load in
// There are other application scenarios for this method , For example, write a hyperlink <a href="tel:110"> Contact us </a>, When clicking the hyperlink , You can get the link address in this method tel:110, Resolve the address , Get the phone number , Then jump to the local call page , Instead of loading web pages , So that webView Interaction with local code
return true;
}
});- Set up WebChromeClient
mWebView.setWebChromeClient(new WebChromeClient() {
@Override
public void onProgressChanged(WebView view, int newProgress) {
super.onProgressChanged(view, newProgress);
// Progress changes
System.out.println(" speed of progress :" + newProgress);
}
@Override
public void onReceivedTitle(WebView view, String title) {
super.onReceivedTitle(view, title);
// Webpage title
System.out.println(" Webpage title :" + title);
}
});- WebView Load the previous and next pages
mWebView.goBack();// Jump to the previous page
mWebView.goForward();// Skip to the next page
mWebView.canGoBack();// Can I jump to the previous page ( If you return false, The description is on the first page )
mWebView.canGoForward();// Can I jump to the next page ( If you return false, The note is the last page )WebView Advanced usage
- Cache Settings
WebSettings settings = mWebView.getSettings();
// As long as there is , Whether or not it expires , perhaps no-cache, All use the data in the cache
settings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
// Only load cache
settings.setCacheMode(WebSettings.LOAD_CACHE_ONLY);
// according to cache-control Decide whether to retrieve data from the network
settings.setCacheMode(WebSettings.LOAD_DEFAULT);
// Don't load the cache
settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
What is? cache-control?
cache-control Is the response header of the server when requesting a web page , This response header is used to determine the caching policy of the web page .
Common values are public( Everything will be cached ), private( Content is cached only in the private cache ),no-cache( Nothing is cached ),max-age=xxx( The contents of the cache will be in xxx Seconds after the failure ) wait - Clean cache
The easiest way :
mWebView.clearCache(true);
Another way :
// Delete cache folder
File file = CacheManager.getCacheFileBaseDir();
if (file != null && file.exists() && file.isDirectory()) {
for (File item : file.listFiles()) {
item.delete();
}
file.delete();
}
// Delete cache database
context.deleteDatabase("webview.db");
context.deleteDatabase("webviewCache.db");- Cookie Set up
CookieSyncManager.createInstance(this);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
String cookie = "name=xxx;age=18";
cookieManager.setCookie(URL, cookie);
CookieSyncManager.getInstance().sync();- obtain Cookie
CookieManager cookieManager = CookieManager.getInstance();
String cookie = cookieManager.getCookie(URL);- eliminate Cookie
CookieSyncManager.createInstance(context); CookieManager cookieManager = CookieManager.getInstance(); cookieManager.removeAllCookie(); CookieSyncManager.getInstance().sync();Android and Js Interaction
If Js and Android The interaction is realized , Then we can call local Java Code , That's how it works WebView Interaction with local code . once WebView Can operate Android Native code , that WebView Will be more powerful , In the future, we will work directly in one WebView Can almost be achieved Android All functions of ,Android Native controls are useless .
- Js call Android
WebSettings settings = mWebView.getSettings();
settings.setJavaScriptEnabled(true);// Turn on js
mWebView.loadUrl("file:///android_asset/demo.html");// Load local web page
mWebView.setWebChromeClient(new WebChromeClient());// This line of code guarantees js Of alert The pop-up window pops up normally
// The core approach , Used for processing js Callback after being executed
mWebView.addJavascriptInterface(new JsCallback() {
@JavascriptInterface// Be careful : This note must be added here , Otherwise, in the 4.1+ Failed to run on the system
@Override
public void onJsCallback() {
System.out.println("js call Android La ");
}
}, "demo");// ginseng 1 It's the implementation of the callback interface ; ginseng 2 yes js The name of the callback object
// Define callback interface
public interface JsCallback {
public void onJsCallback();
}- Android call Js
// Use it directly webview load js That's all right.
mWebView.loadUrl("javascript:wave()");- Enclosed demo.html Source code
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<script language="javascript"> /* This function is invoked by the activity */ function wave() {
alert("Android call Js La "); } </script>
<body>
<!-- Js call Android Code -->
<a onClick="window.demo.onJsCallback()"><div style="width:80px; margin:0px auto; padding:10px; text-align:center; border:2px solid #202020;" >
<img id="droid" src="android_normal.png"/><br>
Click me!
</div></a>
</body>
</html> Be careful : js The writing format of the callback method : onClick=”window.demo.onJsCallback()
The format is : window.js The name of the callback object ( Want to be with java Consistency of settings in the code ). Callback method name ( Want to be with java Consistency of settings in the code )
- matters needing attention
Js call Android The way has version compatibility problems . After testing , stay 2.2, 4.0+ Stable operation on the system , It can be called normally , But in 2.3 Crash while running on the system . The reason is that the bottom is going on JNI Invocation time , Put one Java Medium String Object when the array comes to access , Eventually, the virtual machine crashes . It's basically a more serious BUG, There's no way , So if we use WebView The component wants to be in js and java If you call each other, you can't adapt to all models .
Reference link :
https://code.google.com/p/android/issues/detail?id=12987
http://www.2cto.com/kf/201108/101375.html
At present, some of the more avant-garde app Just use one WebView As a whole ,app All contents in are used html5 To display . such as 12306 Mobile client . The advantage of doing this is to realize cross platform , Just one copy h5 Code , You can go to Android and Ios Run simultaneously on the platform , And it's easier to update , Just change the server's h5 page , The local client will update synchronously , Don't need to download apk Overlay installation . But the disadvantage is also obvious , h5 Limited by network speed , The loading speed is often slow , No native control fluency , The user experience is poor . So now it's fully used h5 build app It has not become the mainstream way .
- WebView Application scenarios of
WebView We don't need to talk more about the application scenarios of , I only mention one point here : With html5 The popularity of , quite a lot app Will be embedded webview To load the html5 page , and h5 Do and app Native controls are very similar , So how do we recognize the use of a page h5 It is still made with native controls ?
Open developer options , You will see such an option : Display the layout boundary if it is WebView Words , Only in WebView The edge will show a border .
边栏推荐
- Minikube initial experience environment construction
- Article summary of MinGW installation and use
- The reflect mechanism obtains the attribute and method information of class
- Consumer installation and configuration
- 中国业务型CDP白皮书 | 爱分析报告
- [pyGame practice] the super interesting bubble game is coming - may you be childlike and always happy and simple~
- Several reincarnation stories
- Simple selection sort and heap sort
- Multithreading and high concurrency (III) -- source code analysis AQS principle
- AlexNet—论文分析及复现
猜你喜欢

“蔚来杯“2022牛客暑期多校训练营2

使用百度飞桨 EasyDL 完成垃圾分类

Globalthis is not defined solution

可视化大型时间序列的技巧。

简单选择排序与堆排序

Hcip day 1

A hundred flowers bloom in data analysis engines. Why invest heavily in Clickhouse?

14. User web layer services (II)

Distributed system (III) construction of distributed transaction service

Redis安装
随机推荐
Why does acid food hurt teeth + early periodontitis
简单选择排序与堆排序
The game process and the underlying implementation are gradually completed
Client service registration of Nacos registry
【补题日记】[2022牛客暑期多校2]H-Take the Elevator
R language ggplot2 visualization: use the ggdotplot function of ggpubr package to visualize dot plot, set the add parameter, add violin graph to the dot plot, and add the vertical line of mean standar
How to make the characters in the photos laugh? HMS core video editing service one click smile function makes people smile more naturally
Launcher sample code
游戏流程与底层实现 逐步完成
Distributed system (III) construction of distributed transaction service
CentOS 7 install MySQL 5.7 & uninstall MySQL 5.7
[applet] how to notify users of wechat applet version update?
R language ggplot2 visualization: use the ggdotplot function of ggpubr package to visualize the grouped dot plot, set the palette parameter, and set the color of data points in different grouped dot p
String function (Part 2)
STL concept and its application
从0开发一个自己的npm包
Application of mobile face stylization Technology
Several reincarnation stories
【补题日记】[2022牛客暑期多校2]D-Link with Game Glitch
What is WordPress