Android WebView实现缓存

package com.hcy.trining_day6;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;

public class HomeActivity extends AppCompatActivity {

//  实现缓存的路径
    private static final String APP_CACHE_DIRNAME = "/webcache";
    private WebView mView;
    private Toolbar toobarv;
    private  TextView txt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        initView();
    }

    private void initView() {
        mView = (WebView) findViewById(R.id.mView);
        txt = (TextView) findViewById(R.id.txt);

        String data = getIntent().getStringExtra("data");
        String title = getIntent().getStringExtra("title");
        //  设置url
        mView.loadUrl(data);
        //  在本页面跳转浏览器
        mView.setWebViewClient(new WebViewClient());
        initweb();
        toobarv = (Toolbar) findViewById(R.id.toobarv);
        toobarv.setTitle("");
        //  设置标题
        txt.setText(title);
        setSupportActionBar(toobarv);
        //  toobar 回退箭头
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        toobarv.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();// 加finish退出应用
                // 不加finish返回上一层
            }
        });

    }

//  WebView 实现缓存
    private void initweb() {
        WebSettings settings = mView.getSettings();
        settings.setJavaScriptEnabled(true);
//设置缓存模式
        settings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
//开启DOM storage API 功能
        settings.setDomStorageEnabled(true);
//开启 database storage API 功能
        settings.setDatabaseEnabled(true);
        String cachePath = getFilesDir().getAbsolutePath() + APP_CACHE_DIRNAME;
//设置数据库缓存路径
        settings.setAppCachePath(cachePath);
        settings.setAppCacheEnabled(true);
        mView.reload();
    }
}

你可能感兴趣的:(Android)