学习进度5

浏览器都可以缓存网页的一些图片文字之类的为了下次能够快速的加载出网页。
上代码,先说明这个不用加文件修改权限因为这算是处于应用私有文件夹,不算是手机用户的,修改时不需要权限同意,还有就是布局代码一样。

public class MainActivity extends Activity {
/** Called when the activity is first created. */
private WebView webView;
private Button button;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

init();

}


private void init(){
webView = (WebView) findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT); //设置 缓存模式
// 开启 DOM storage API 功能
webView.getSettings().setDomStorageEnabled(true);
//开启 database storage API 功能
webView.getSettings().setDatabaseEnabled(true);
String cacheDirPath = getFilesDir().getAbsolutePath()+"myWeb";
// String cacheDirPath = getCacheDir().getAbsolutePath()+Constant.APP_DB_DIRNAME;
Log.i("zzw", "cacheDirPath=" + cacheDirPath);
//设置数据库缓存路径
webView.getSettings().setDatabasePath(cacheDirPath);
//设置 Application Caches 缓存目录
webView.getSettings().setAppCachePath(cacheDirPath);
//开启 Application Caches 功能
webView.getSettings().setAppCacheEnabled(true);
//WebView加载web资源
webView.loadUrl("http://baidu.com");
//覆盖WebView默认使用第三方或系统默认浏览器打开网页的行为,使网页用WebView打开
webView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub

view.loadUrl(url);
//返回值是true的时候控制去WebView打开,是false调用系统浏览器或第三方浏览器
return true;
}
});
}

@Override
protected void onDestroy() {
super.onDestroy();
clearWebViewCache();
}

/**
* 清除WebView缓存
*/
public void clearWebViewCache(){

//清理Webview缓存数据库
try {
deleteDatabase("webview.db");
deleteDatabase("webviewCache.db");
} catch (Exception e) {
e.printStackTrace();
}

//WebView 缓存文件
File appCacheDir = new File(getFilesDir().getAbsolutePath()+"myWeb");
Log.e("zzw", "appCacheDir path=" + appCacheDir.getAbsolutePath());

File webviewCacheDir = new File(getCacheDir().getAbsolutePath()+"/webviewCache");
Log.e("zzw", "webviewCacheDir path=" + webviewCacheDir.getAbsolutePath());

//删除webview 缓存目录
if(webviewCacheDir.exists()){
deleteFile(webviewCacheDir.toString());
}
//删除webview 缓存 缓存目录
if(appCacheDir.exists()){
deleteFile(appCacheDir.toString());
}
}

 

}

posted @ 2021-06-10 23:13  我好cai  阅读(26)  评论(0编辑  收藏  举报