在Activity中WebView的基础设置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| WebSettings settings = mWebView.getSettings(); settings.setBuiltInZoomControls(true); settings.setUseWideViewPort(true); settings.setJavaScriptEnabled(true); settings.setJavaScriptCanOpenWindowsAutomatically(true); settings.setAllowFileAccess(true); settings.setAppCacheEnabled(false); settings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); settings.setAllowUniversalAccessFromFileURLs(true); settings.setUseWideViewPort(true); settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS); settings.setLoadWithOverviewMode(true); settings.setDomStorageEnabled(true); settings.setSupportZoom(false); settings.setBuiltInZoomControls(false);
|
其他设置
修改urerAgent()
1 2
| String urerAgent = settings.getUserAgentString(); settings.setUserAgentString(urerAgent + "XXX(前端需要你添加的一些标识)");
|
这里主要记录一下自己项目中碰到的问题
** 退出当前界面时 WebView还在播放音乐或者视频,finish当前Activity也不管用**
解决方法:在Activity的onDestroy释放WebView
1 2 3 4 5 6 7
| @Override protected void onDestroy() { if (mWebView != null) { mWebView.destroy(); } super.onDestroy(); }
|
开启缓存的前提下数据被缓存 一般可以直接调用下面方法进行缓存清除
比如设置了
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| WebSettings settings = mWebView.getSettings(); settings.setAppCacheEnabled(true); settings.setCacheMode(WebSettings.LOAD_DEFAULT); settings.setDomStorageEnabled(true); settings.setDatabaseEnabled(true); String cacheDirPath = getFilesDir().getAbsolutePath()+APP_CACAHE_DIRNAME; settings.setDatabasePath(cacheDirPath); settings.setAppCachePath(cacheDirPath);
|
直接调用下面方法就可以清除缓存
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
|
public void clearWebViewCache(){ try { deleteDatabase("webview.db"); deleteDatabase("webviewCache.db"); } catch (Exception e) { e.printStackTrace(); } File appCacheDir = new File(getFilesDir().getAbsolutePath()+APP_CACAHE_DIRNAME); Log.e(TAG, "appCacheDir path="+appCacheDir.getAbsolutePath()); File webviewCacheDir = new File(getCacheDir().getAbsolutePath()+"/webviewCache"); Log.e(TAG, "webviewCacheDir path="+webviewCacheDir.getAbsolutePath()); if(webviewCacheDir.exists()){ deleteFile(webviewCacheDir); } if(appCacheDir.exists()){ deleteFile(appCacheDir); } }
|
可是假如设置了不开启缓存 每次就算后台改了WebView的url数据还是被缓存呢?
1 2
| WebSettings settings = mWebView.getSettings(); settings.setAppCacheEnabled(true);
|
调用下面方法试试吧
1 2 3 4 5 6 7 8 9
| public void clearCache(){ try { deleteDatabase("webview.db"); deleteDatabase("webviewCache.db"); } catch (Exception e) { e.printStackTrace(); } }
|
关于WebView使用的其他问题碰到再记录下来