android webview 缓存无网络

public class ZhiBoFragment extends BaseFragment {
    private Context context;
    private ProgressWebView webView;---这里是我自定义的Webview,你们可以不用直接用系统的就行
    private String HSH_URL = "https://wap.baidu.com/";
//    private String HSH_URL = "http://www.youdao.com/";
//    private String HSH_URL = AppUrl.Main_url;

    @Override
    protected View initView() {
        context = getActivity();
        View view = View.inflate(context, R.layout.fragment_zhibo, null);
        webView = (ProgressWebView) view.findViewById(R.id.web_webview);
        return view;
    }

    @Override
    protected void initData() {
        webView.requestFocus();
        webView.setHorizontalScrollBarEnabled(false);
        webView.setVerticalScrollBarEnabled(false);
        webView.setWebChromeClient(new WebChromeClient());
        //webView.loadUrl(HSH_URL);
//        webView.setWebViewClient(new WebViewClient() {
//            @Override
//            public boolean shouldOverrideUrlLoading(WebView view, String url) {
//                if (url.startsWith("http:") || url.startsWith("https:")) {
//                    view.loadUrl(url);
//                    return false;
//                } else {
//                    return true;
//                }
//            }
//        });
        webView.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View view, int keyCode, KeyEvent event) {
                if (event.getAction() == KeyEvent.ACTION_DOWN) {
                    if (keyCode == KeyEvent.KEYCODE_BACK) {
                        if (webView.canGoBack()) {
                            webView.goBack();
                            return true;
                        }
                    }
                }
                return false;
            }
        });
        initWebView();
      //  postZiBo();
    }
	不用管这个方法,这是请求聚合支付用的
    private void postZiBo() {
        new Thread() {
            @Override
            public void run() {
                OkHttpUtils.post().url(AppUrl.EEE)
                        .addParams("username", Base64Utils.getBase64("18662282856"))
                        .addParams("password", Base64Utils.getBase64("123456"))
                        .build()
                        .execute(new MyBeanCallBack() {
                            @Override
                            public Object parseNetworkResponse(Response response, int id) throws Exception {

                                String string = response.body().string();

                                Log.e("=====聚合数据", Base64Utils.getFromBase64(string));
                                return super.parseNetworkResponse(response, id);
                            }
                        });
            }
        }.start();

    }
    @SuppressWarnings("deprecation")
    @SuppressLint("SetJavaScriptEnabled")
    private void initWebView() {

        webView.getSettings().setJavaScriptEnabled(true);
        // 设置 缓存模式
        if (AppUtils.isNetworkAvailable(context)) {
            webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
        } else {
            webView.getSettings().setCacheMode(
                    WebSettings.LOAD_CACHE_ELSE_NETWORK);
        }
        // webView.getSettings().setBlockNetworkImage(true);// 把图片加载放在最后来加载渲染
        webView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
        // 支持多窗口
        webView.getSettings().setSupportMultipleWindows(true);
        // 开启 DOM storage API 功能
        webView.getSettings().setDomStorageEnabled(true);
        // 开启 Application Caches 功能
        webView.getSettings().setAppCacheEnabled(true);
        onLoad();
    }
    @SuppressWarnings("deprecation")
    @SuppressLint("SetJavaScriptEnabled")
    public void onLoad() {
        try {
            webView.setWebViewClient(new WebViewClient() {
                @Override
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
			这里是用来处理Url类型的,
                    if (url.startsWith("http:") || url.startsWith("https:")) {
                        view.loadUrl(url);
                        return false;
                    } else {
                        return true;
                    }
                }
            });
            webView.loadUrl(HSH_URL);
        } catch (Exception e) {
            return;
        }
    }
    /***
     * 防止WebView加载内存泄漏
     */
    @Override
    public void onDestroy() {
        super.onDestroy();
        webView.removeAllViews();
        webView.destroy();
    }
}
以上是主要的代码,下边是我自定义的webview,你们参考参考就行,不一定要用我的
public class ProgressWebView extends WebView {
    private WebViewProgressBar progressBar;//进度条的矩形(进度线)
    private Handler handler;
    private WebView mWebView;

    public ProgressWebView(Context context, AttributeSet attrs) {
        super(context, attrs);
        //实例化进度条
        progressBar = new WebViewProgressBar(context);
        //设置进度条的size
        progressBar.setLayoutParams(new ViewGroup.LayoutParams
                (ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        //刚开始时候进度条不可见
        progressBar.setVisibility(GONE);
        //把进度条添加到webView里面
        addView(progressBar);
        //初始化handle
        handler = new Handler();
        mWebView = this;
        initSettings();
    }

    private void initSettings() {
        // 初始化设置
        WebSettings mSettings = this.getSettings();
        mSettings.setJavaScriptEnabled(true);//开启javascript
        mSettings.setDomStorageEnabled(true);//开启DOM
        mSettings.setDefaultTextEncodingName("utf-8");//设置字符编码
        //设置web页面
        mSettings.setAllowFileAccess(true);//设置支持文件流
        mSettings.setSupportZoom(true);// 支持缩放
        mSettings.setBuiltInZoomControls(true);// 支持缩放
        //不显示webview缩放按钮
        mSettings.setDisplayZoomControls(false);
        mSettings.setUseWideViewPort(true);// 调整到适合webview大小
        mSettings.setLoadWithOverviewMode(true);// 调整到适合webview大小
        // 屏幕自适应网页,如果没有这个,在低分辨率的手机上显示可能会异常
        mSettings.setDefaultZoom(WebSettings.ZoomDensity.FAR);
        mSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);
        //提高网页加载速度,暂时阻塞图片加载,然后网页加载好了,在进行加载图片
//        mSettings.setBlockNetworkImage(true);
        mSettings.setAppCacheEnabled(true);//开启缓存机制
        setWebViewClient(new MyWebClient());
        setWebChromeClient(new MyWebChromeClient());
    }

    /**
     * 自定义WebChromeClient
     */
    private class MyWebChromeClient extends WebChromeClient {
        /**
         * 进度改变的回掉
         *
         * @param view        WebView
         * @param newProgress 新进度
         */
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (newProgress == 100) {
                progressBar.setProgress(100);
                handler.postDelayed(runnable, 200);//0.2秒后隐藏进度条
            } else if (progressBar.getVisibility() == GONE) {
                progressBar.setVisibility(VISIBLE);
            }
            //设置初始进度10,这样会显得效果真一点,总不能从1开始吧
            if (newProgress < 10) {
                newProgress = 10;
            }
            //不断更新进度
            progressBar.setProgress(newProgress);
            super.onProgressChanged(view, newProgress);
        }
    }

    private class MyWebClient extends WebViewClient {
        /**
         * 加载过程中 拦截加载的地址url
         *
         * @param view
         * @param url  被拦截的url
         * @return
         */
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            mWebView.loadUrl(url);
            return true;
        }

        /**
         * 页面加载过程中,加载资源回调的方法
         *
         * @param view
         * @param url
         */
        @Override
        public void onLoadResource(WebView view, String url) {
            super.onLoadResource(view, url);
        }

        /**
         * 页面加载完成回调的方法
         *
         * @param view
         * @param url
         */
        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            // 关闭图片加载阻塞
            view.getSettings().setBlockNetworkImage(false);
        }

        /**
         * 页面开始加载调用的方法
         *
         * @param view
         * @param url
         * @param favicon
         */
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
        }

        @Override
        public void onScaleChanged(WebView view, float oldScale, float newScale) {
            super.onScaleChanged(view, oldScale, newScale);
            ProgressWebView.this.requestFocus();
            ProgressWebView.this.requestFocusFromTouch();
        }
    }

    /**
     * 刷新界面(此处为加载完成后进度消失)
     */
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            progressBar.setVisibility(View.GONE);
        }
    };
}
public class WebViewProgressBar extends View {
    private int progress = 1;//进度默认为1
    private final static int HEIGHT = 5;//进度条高度为5
    private Paint paint;//进度条的画笔
    //  private final static int colors[] = new int[]{0xFF7AD237, 0xFF8AC14A, 0x35B056 };

    public WebViewProgressBar(Context context) {
        this(context, null);
    }

    public WebViewProgressBar(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public WebViewProgressBar(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initPaint(context);
    }

    private void initPaint(Context context) {
        //颜色渐变从colors[0]到colors[2],透明度从0到1
//        LinearGradient shader = new LinearGradient(
//                0, 0,
//                100, HEIGHT,
//                colors,
//                new float[]{0 , 0.5f, 1.0f},
//                Shader.TileMode.MIRROR);
        paint = new Paint(Paint.DITHER_FLAG);
        paint.setStyle(Paint.Style.STROKE);// 填充方式为描边
        paint.setStrokeWidth(HEIGHT);//设置画笔的宽度
        paint.setAntiAlias(true);// 抗锯齿
        paint.setDither(true);// 使用抖动效果
        paint.setColor(context.getResources().getColor(R.color.colorPrimaryDark));//画笔设置颜色
//        paint.setShader(shader);//画笔设置渐变
    }

    /**
     * 设置进度
     *
     * @param progress 进度值
     */
    public void setProgress(int progress) {
        this.progress = progress;
        invalidate();//刷新画笔
    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.drawRect(0, 0, getWidth() * progress / 100, HEIGHT, paint);//画矩形从(0.0)开始到(progress,height)的区域
    }
}

下面是我的工具类
public class AppUtils {
    /**
     * 判断是否安装微信
     *
     * @param context
     * @return
     */
    public static boolean isWeixinAvilible(Context context) {
        final PackageManager packageManager = context.getPackageManager();// 获取packagemanager
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equals("com.tencent.mm")) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 一个可以连续弹出的吐司
     *
     * @param context
     * @param string
     */
    public static void getToast(Context context, String string) {
        try {
            Toast toast = Toast.makeText(context, string, Toast.LENGTH_SHORT);
            LinearLayout linearLayout = (LinearLayout) toast.getView();
            TextView messageTextView = (TextView) linearLayout.getChildAt(0);
            messageTextView.setTextSize(15);
            toast.show();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 动态获取开发权限
     * WRITE_EXTERNAL_STORAGE===开启内存权限
     * CALL_PHONE ===开启拨打电话权限
     * ACCESS_COARSE_LOCATION===开启蓝牙权限
     */
    public static void requestPermission(final Context c) {
        BaseActivity.requestRunTimePermission(new String[]{
                        Manifest.permission.CALL_PHONE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.ACCESS_COARSE_LOCATION,
                        Manifest.permission.CAMERA,
                        Manifest.permission.READ_EXTERNAL_STORAGE
                }
                , new PermissionListener() {
                    @Override
                    public void onGranted() {
                    }

                    @Override
                    public void onGranted(List<String> grantedPermission) {
                    }

                    @Override
                    public void onDenied(List<String> deniedPermission) {
                    }
                });
    }

    /**
     * d
     * 判断是否有网
     *
     * @param context
     * @return
     */
    public static boolean IsHaveInternet(final Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager
                    .getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isAvailable();
            }
        }
        return false;
    }
    /**
     * 打开权限设置界面
     */
//    public void openSetting(final Context context) {
//        try {
//            Intent localIntent = new Intent(
//                    "miui.intent.action.APP_PERM_EDITOR");
//            localIntent.setClassName("com.miui.securitycenter",
//                    "com.miui.permcenter.permissions.AppPermissionsEditorActivity");
//            localIntent.putExtra("extra_pkgname", context.getPackageName());
//            cstartActivityForResult(localIntent, 11);
//            context.startActivity(localIntent);
//        } catch (ActivityNotFoundException localActivityNotFoundException) {
//            //ACTION_MANAGE_WRITE_SETTINGS
//            //.ACTION_MANAGE_OVERLAY_PERMISSION==跳转到设置应用权限管理界面
//            //ACTION_APPLICATION_DETAILS_SETTINGS===跳转到设置应用信息界面
//            Intent intent1 = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
//            Uri uri = Uri.fromParts("package", context.getPackageName(), null);
//            intent1.setData(uri);
//            startActivityForResult(intent1, 11);
//        }
//    }

    /**
     * 判断悬浮窗权限
     *
     * @param context
     * @return
     */
    @TargetApi(Build.VERSION_CODES.KITKAT)
    public static boolean isFloatWindowOpAllowed(Context context) {
        final int version = Build.VERSION.SDK_INT;
        if (version >= 19) {
            return checkOp(context, 24); // AppOpsManager.OP_SYSTEM_ALERT_WINDOW
        } else {
            if ((context.getApplicationInfo().flags & 1 << 27) == 1 << 27) {
                return true;
            } else {
                return false;
            }
        }
    }

    @TargetApi(Build.VERSION_CODES.KITKAT)
    public static boolean checkOp(Context context, int op) {
        final int version = Build.VERSION.SDK_INT;
        if (version >= 19) {
            AppOpsManager manager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
            try {
//                ClassspClazz = Class.forName(manager.getClass().getName());
                Class ClassspClazz = Class.forName(manager.getClass().getName());
                Method method = manager.getClass().getDeclaredMethod("checkOp", int.class, int.class, String.class);
                int property = (Integer) method.invoke(manager, op,
                        Binder.getCallingUid(), context.getPackageName());
                Log.e("399", " property: " + property);
                if (AppOpsManager.MODE_ALLOWED == property) {
                    return true;
                } else {
                    return false;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            Log.e("399", "Below API 19 cannot invoke!");
        }
        return false;
    }


    /**
     * 我的小区提示弹窗
     *
     * @param mContext
     * @return
     */
    public static Dialog community(final Context mContext) {
        Dialog modlg = new Dialog(mContext, R.style.DialogStyleBottom);
        View view = View.inflate(mContext, R.layout.photo, null);
        ImageView iv_image = (ImageView) view.findViewById(R.id.iv_picture);
        iv_image.setImageResource(R.mipmap.xiaoqu);
        Button btn_pages = (Button) view.findViewById(R.id.btn_home_page);
        btn_pages.setText("我的小区");
        btn_pages.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent in = new Intent(mContext, HomepageActivity.class);
                in.putExtra("url", "Mobile/District/myDistrict.html");
                mContext.startActivity(in);
            }
        });
        modlg.setContentView(view);
        modlg.setCanceledOnTouchOutside(true);//触摸其他地方不消失
        modlg.setCancelable(true);// 不可以用“返回键”取消
        Window dialogWindow = modlg.getWindow();
        dialogWindow.setGravity(Gravity.CENTER);
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.y = 10;
        dialogWindow.setAttributes(lp);
        modlg.show();
        return modlg;
    }

    /**
     * 自定义等待加载弹窗
     *
     * @param context
     * @return
     */
    public static Dialog createLoadingDialog(Context context) {
        LayoutInflater inflater = LayoutInflater.from(context);
        View v = inflater.inflate(R.layout.loading_dialog, null);// 得到加载view
        // LinearLayout layout = (LinearLayout) v.findViewById(R.id.dialog_view);// 加载布局
        LinearLayout layout = (LinearLayout) v.findViewById(R.id.dialog_view);
        // main.xml中的ImageView
        ImageView spaceshipImage = (ImageView) v.findViewById(R.id.img);
//        TextView tipTextView = (TextView) v.findViewById(R.id.tipTextView);// 提示文字
        // 加载动画
        Animation hyperspaceJumpAnimation = AnimationUtils.loadAnimation(
                context, R.anim.loading_animation);
        // 使用ImageView显示动画
        spaceshipImage.startAnimation(hyperspaceJumpAnimation);
        //  tipTextView.setText(msg);// 设置加载信息

        Dialog loadingDialog = new Dialog(context, R.style.loading_dialog);// 创建自定义样式dialog

        loadingDialog.setCancelable(true);// 不可以用“返回键”取消
        loadingDialog.setContentView(layout, new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT));// 设置布局
        return loadingDialog;

    }
//
//    public static void TanChuang(final Context context) throws Exception {
//        new AlertDialog.Builder(context)
//                .setTitle(R.string.notTitle)
//                .setMessage(DataCleanManager.getTotalCacheSize(context))
                // 拒绝, 退出应用
//                .setNegativeButton(R.string.notQuXiao,
//                        new DialogInterface.OnClickListener() {
//                            @Override
//                            public void onClick(DialogInterface dialog, int which) {
//                            }
//                        })
//
//                .setPositiveButton(R.string.notQueRen,
//                        new DialogInterface.OnClickListener() {
//                            @Override
//                            public void onClick(DialogInterface dialog, int which) {
//                                DataCleanManager.clearAllCache(context);
                                //跳转到下载界面
                                Uri uri = Uri.parse("http://www.efu168.cn/app/index.html?from=singlemessage");
                                Intent it = new Intent(Intent.ACTION_VIEW, uri);
                                context.startActivity(it);
//                            }
//                        })
//
//                .setCancelable(true)
//                .show();
//
//    }

    /**
     * 提示框
     *
     * @param context
     * @throws Exception
     */
//    public static void PromPting(final Context context) throws Exception {
//        new AlertDialog.Builder(context)
//                .setTitle(R.string.notTitle)
//                .setMessage("支付成功")
//                .setPositiveButton(R.string.notQueRen,
//                        new DialogInterface.OnClickListener() {
//                            @Override
//                            public void onClick(DialogInterface dialog, int which) {
//
                                //跳转到下载界面
                                Uri uri = Uri.parse("http://www.efu168.cn/app/index.html?from=singlemessage");
                                Intent it = new Intent(Intent.ACTION_VIEW, uri);
                                context.startActivity(it);
//                            }
//                        })
//
//                .setCancelable(true)
//                .show();
//
//    }

    /**
     * @param context
     */
//    public static void TiShi(Context context) {
//        new AlertDialog.Builder(context)
//                .setTitle("悬浮窗权限管理")
//                .setMessage("是否去开启悬浮窗权限?")
//                .setPositiveButton("是", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialogInterface, int i) {
//                    }
//                })
//                .setNegativeButton("否", null)
//                .create();
//    }

    /**
     * 用户取消授权悬浮按钮权限弹窗
     *
     * @param context
     * @return
     */
    public static Dialog indexDialog(final Context context) {
        Dialog modlg = new Dialog(context, R.style.DialogStyleBottom);
        View view = View.inflate(context, R.layout.photo_index, null);
        modlg.setContentView(view);
        modlg.setCanceledOnTouchOutside(true);//触摸其他地方不消失
        modlg.setCancelable(true);// 不可以用“返回键”取消
        Window dialogWindow = modlg.getWindow();
        dialogWindow.setGravity(Gravity.BOTTOM);
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.y = 10;
        dialogWindow.setAttributes(lp);
        modlg.show();
        return modlg;
    }

    /**
     * 用户可以在一下小区解锁
     *
     * @param context
     * @return
     */
//    public static Dialog CommunityDialog(final Context context) {
//        Dialog modlg = new Dialog(context, R.style.DialogStyleBottom);
//        View view = View.inflate(context, R.layout.photo_community, null);
//        ListView listview = (ListView) view.findViewById(R.id.lv_com_listview);
//        CommunityAdapter comAdapter = new CommunityAdapter(context);
//        //comAdapter.setList();
//        listview.setAdapter(comAdapter);
//        modlg.setContentView(view);
//        modlg.setCanceledOnTouchOutside(true);//触摸其他地方不消失
//        modlg.setCancelable(true);// 不可以用“返回键”取消
//        Window dialogWindow = modlg.getWindow();
//        dialogWindow.setGravity(Gravity.BOTTOM);
//        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
//        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
//        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
//        lp.y = 10;
//        dialogWindow.setAttributes(lp);
//        modlg.show();
//        return modlg;
//    }

}
希望会对你们有所帮助,811839095这是我的qq号,有不懂得地方咱们可以交流。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值