webview交互和缓存分析

该遍文章的webview与js的交互主要是,js调用到Android里的webview(在最后面附上源码)


1.需要在网页版的js里写好要交互的函数接口,例如我现在要网页版那边给我传来一个地址,

则在网页版的js写好:

window.jump.XXX()的格式,jump也是可以自定义的。


我这边的js需要调用的接口是:

window.jump.gotoService(path);

widow.jump.gotoRegService(path);


2.在webview的android代码这边写上

mWebview.addJavascriptInterface(new WebAppInterface(mContext),"jump");
第一个参数是自定义的内部类名称,第二个参数是js网页版对应的的第二个参数名称,该名称可以自定义,

但是一定要跟网页版的第二个参数定义保持一致。


WebAppInterface类:
 
class WebAppInterface{
        private Context context;
        public WebAppInterface(Context ct){
            this.context = ct;
        }

        @JavascriptInterface
        public void gotoService(String path){
            openBrowser(path);
        }

        @JavascriptInterface
        public void gotoRegService(String path){
            openBrowser(path);
        }

        private void openBrowser(String path) {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setData(Uri.parse(path));
            context.startActivity(intent);
        }
    }


3.

在我们开发过程中,有可能会遇到webview有些网页打不开的问题。这可能是设置的不对,下面就是解决办法。

进行如下设置吧,大多数情况都能解决!

displayWebview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);//设置js可以直接打开窗口,如window.open(),默认为false
displayWebview.getSettings().setJavaScriptEnabled(true);//是否允许执行js,默认为false。设置true时,会提醒可能造成XSS漏洞
displayWebview.getSettings().setSupportZoom(true);//是否可以缩放,默认true
displayWebview.getSettings().setBuiltInZoomControls(true);//是否显示缩放按钮,默认false
displayWebview.getSettings().setUseWideViewPort(true);//设置此属性,可任意比例缩放。大视图模式
displayWebview.getSettings().setLoadWithOverviewMode(true);//和setUseWideViewPort(true)一起解决网页自适应问题
displayWebview.getSettings().setAppCacheEnabled(true);//是否使用缓存
displayWebview.getSettings().setDomStorageEnabled(true);//DOM Storage
// displayWebview.getSettings().setUserAgentString("User-Agent:Android");//设置用户代理,一般不用

    缓存不开启的时候,可能会有一些使用了这些存储的网页无法打开。


4.WebView缓存分析

WebView的缓存可以分为页面缓存和数据缓存。

页面缓存是指加载一个网页时的html、JS、CSS等页面或者资源数据。这些缓存资源是由于浏览器的行为而产生,开发者只能通过配置HTTP响应头影响浏览器的行为才能间接地影响到这些缓存数据。

他们的索引存放在/data/data/package_name/databases下。他们的文件存放在/data/data/package_name/cache/xxxwebviewcachexxx下。文件夹的名字在2.x和4.x上有所不同,但都文件夹名字中都包含webviewcache。


数据缓存分为两种:AppCache和DOM Storage(Web Storage)。他们是因为页面开发者的直接行为而产生。所有的缓存数据都由开发者直接完全地掌控。
AppCache使我们能够有选择的缓冲web浏览器中所有的东西,从页面、图片到脚本、css等等。尤其在涉及到应用于网站的多个页面上的CSS和JavaScript文件的时候非常有用。其大小目前通常是5M。
在Android上需要手动开启(setAppCacheEnabled),并设置路径(setAppCachePath)和容量(setAppCacheMaxSize)
Android中Webkit使用一个db文件来保存AppCache数据(my_path/ApplicationCache.db)
更详细的资料可以参考这里:http://www.itboat.net/thread-23674-1-1.html

如果需要存储一些简单的用key/value对即可解决的数据,DOM Storage是非常完美的方案。根据作用范围的不同,有Session Storage和Local Storage两种,分别用于会话级别的存储(页面关闭即消失)和本地化存储(除非主动删除,否则数据永远不会过期)。
在Android中可以手动开启DOM Storage(setDomStorageEnabled),设置存储路径(setDatabasePath)
Android中Webkit会为DOM Storage产生两个文件(my_path/localstorage/http_h5.m.taobao.com_0.localstorage和my_path/localstorage/Databases.db)。

另外,在Android中清除缓存时,如果需要清除Local Storage的话,仅仅删除Local Storage的本地存储文件是不够的,内存里面有缓存数据。如果再次进入页面,Local Storage中的缓存数据同样存在。需要杀死程序运行的当前进程再重新启动才可以。
5.源码
public class ShowWebview {
    private static final String URL = "http://192.168.0.55:801/index.html";
    private static final String APP_CACAHE_DIRNAME = "/webcache";
    private WebSettings settings;
    private WebView mWebview;
    private Context mContext;

    public ShowWebview(Context context,WebView webView){
        mContext = context;
        mWebview = webView;
    }

    /*加载HTML网页*/
    public void loadHtml() {
        mWebview.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY); // 设置无边框
        settings = mWebview.getSettings();
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);//web内容强制满屏
        settings.setUseWideViewPort(true);
        settings.setLoadWithOverviewMode(true);
        settings.setJavaScriptEnabled(true);
        settings.setJavaScriptCanOpenWindowsAutomatically(true);//设置js可以直接打开窗口,如window.open(),默认为false
        settings.setLoadWithOverviewMode(true);//和setUseWideViewPort(true)一起解决网页自适应问题

        //覆盖WebView默认使用第三方或系统默认浏览器打开网页的行为,使网页用WebView打开
        mWebview.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                // TODO Auto-generated method stub
                //返回值是true的时候控制去WebView打开,为false调用系统浏览器或第三方浏览器
                view.loadUrl(URL);
                return true;
            }
        });
        mWebview.loadUrl(URL);
        //设置webview缓存
        setWebviewCache();

        mWebview.addJavascriptInterface(new WebAppInterface(mContext),"jump");
    }

    /*设置webview缓存*/
    private void setWebviewCache(){
        settings.setRenderPriority(WebSettings.RenderPriority.HIGH);
        settings.setAppCacheEnabled(true);//是否使用缓存
        settings.setCacheMode(WebSettings.LOAD_DEFAULT);  //设置 缓存模式
        // 开启 DOM storage API 功能,支持 H5 的session storage和local storage
        settings.setDomStorageEnabled(true);
        //开启 database storage API 功能
        settings.setDatabaseEnabled(true);
        String cacheDirPath = mContext.getFilesDir().getAbsolutePath()+APP_CACAHE_DIRNAME;
//      String cacheDirPath = getCacheDir().getAbsolutePath()+Constant.APP_DB_DIRNAME;
//        Log.i(TAG, "cacheDirPath="+cacheDirPath);
        //设置数据库缓存路径
        settings.setDatabasePath(cacheDirPath);
        //设置  Application Caches 缓存目录
        settings.setAppCachePath(cacheDirPath);
        //开启 Application Caches 功能
        settings.setAppCacheEnabled(true);
    }

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

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

        //WebView 缓存文件
        File appCacheDir = new File(mContext.getFilesDir().getAbsolutePath()+APP_CACAHE_DIRNAME);

        File webviewCacheDir = new File(mContext.getCacheDir().getAbsolutePath()+"/webviewCache");

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

    /**
     * 递归删除 文件/文件夹
     *
     * @param file
     */
    public void deleteFile(File file) {


        if (file.exists()) {
            if (file.isFile()) {
                file.delete();
            } else if (file.isDirectory()) {
                File files[] = file.listFiles();
                for (int i = 0; i < files.length; i++) {
                    deleteFile(files[i]);
                }
            }
            file.delete();
        } else {
            //Log.e("WebView", "delete file no exists " + file.getAbsolutePath());
        }
    }

    class WebAppInterface{
        private Context context;
        public WebAppInterface(Context ct){
            this.context = ct;
        }

        @JavascriptInterface
        public void gotoService(String path){
            openBrowser(path);
        }

        @JavascriptInterface
        public void gotoRegService(String path){
            openBrowser(path);
        }

        private void openBrowser(String path) {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setData(Uri.parse(path));
            context.startActivity(intent);
        }
    }
}





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值