布局文件:
<WebView
android:id="@+id/webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
Java 代码:
WebView mWebView = findViewById(R.id.webview);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.loadUrl("https://www.baidu.com");
当你玩完成以上步骤之后,就可以加载网页。到这里还没有结束,接下的才是本文的重点。
mWebView.getSettings().setDomStorageEnabled(true);
官方描述:
Sets whether the DOM storage API is enabled. The default value is false.
Parameters
flag true if the WebView should use the DOM storage API
具体是什么意思呢?顾名思义就是设置允许web网页调用localStorage函数,本地存储一些数据。
默认是false,如果不设置为true,当网页调用localStorage.getItem()/setItem()函数时,则会报错。
当你做混合开发,App集成了网页时,这个时候出现问题,需要调试,这个时候就需要开启以下功能,否则前端同事通过 chrome://inspect/#devices 根本无法发现你打开的页面。
此接口在Android4.4以上版本才支持。
if (Build.VERSION.SDK_INT >=Build.VERSION_CODES.KITKAT) {
mWebView.getSettings().setWebContentsDebuggingEnabled(true);
}
release版本记得关闭此功能哦,可以这样写。
if (Build.VERSION.SDK_INT >=Build.VERSION_CODES.KITKAT) {
mWebView.getSettings().setWebContentsDebuggingEnabled(BuildConfig.DEBUG);
}
WebView缓存清空:
可以设置:
mWebView.getSettings().setAppCacheEnabled(false);
mWebView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
退出页面是调用:
mWebView.clearHistory();
mWebView.clearCache(true);
但是,我遇到过调用这些方法更新无效,也有网友是这么实现的:
设置网页的缓存地址,退出页面的数据在请求当前路径下的网页信息。我各人使用了也是没有效果,不知道是否我操作的有问题。
webView.getSettings().setAppCachePath(getApplicationContext().getCacheDir().getPath());
webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
不过这个API到给了我启发,那就从webview默认的缓存路径着手,直接清空下面的缓存数据。
查阅资料得知webview的缓存数据是存放在此路径下:"/data/data/{packagename}/app_webview" 。
那就好办了,直接删除该目录下的文件列表,完美解决。
不过这个目录需要root权限,因为App是在机顶盒上开发,自己定制的Android系统,所以有root权限。