WebView的基类

/**
 * 程序webview基类
 */
@SuppressLint({ "SetJavaScriptEnabled", "DefaultLocale", "NewApi" })
public class WebBaseActivity extends FragmentActivity {

    protected Context context;
    protected WebView webView;
    private final String[][] MIME_table = {
            // 该项目需要打开的几种文件类型{后缀名,MIME类型}
            { ".bmp", "image/bmp" },
            { ".doc", "application/msword" },
            { ".docx",
                    "application/vnd.openxmlformats-officedocument.wordprocessingml.document" },
            { ".xls", "application/vnd.ms-excel" },
            { ".xlsx",
                    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" },
            { ".gif", "image/gif" },
            { ".jpeg", "image/jpeg" },
            { ".jpg", "image/jpeg" },
            { ".pdf", "application/pdf" },
            { ".png", "image/png" },
            { ".ppt", "application/vnd.ms-powerpoint" },
            { ".pptx",
                    "application/vnd.openxmlformats-officedocument.presentationml.presentation" },
            { ".txt", "text/plain" }, { "", "*/*" } };

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_webview);
        context = this;
    }

    /**
     * 初始化控件以及webview基本设置
     */
    @SuppressWarnings("deprecation")
    protected void initWebView() {
        webView = (WebView) findViewById(R.id.webview_view);

        webView.setInitialScale(1);
        // 全屏显示
        webView.getSettings().setLoadWithOverviewMode(true);
        // 开启缩放控件的缩放
        webView.getSettings().setSupportZoom(true);
        // webView.getSettings().setLayoutAlgorithm(LayoutAlgorithm.NARROW_COLUMNS);
        // 自动适应屏幕,支持两手滑动缩放
        webView.getSettings().setUseWideViewPort(true);

        // 开启缩放控件
        webView.getSettings().setBuiltInZoomControls(true);

        // 支持多窗口
        webView.getSettings().setSupportMultipleWindows(true);
        // webView设置启用JavaScript.
        webView.getSettings().setJavaScriptEnabled(true);

        // 开启自动加载图片
        webView.getSettings().setLoadsImagesAutomatically(true);
        // 显示网络图片
        webView.getSettings().setBlockNetworkImage(false);
        // 渲染优先级
        webView.getSettings().setRenderPriority(RenderPriority.HIGH);
        // 默认字体大小
        // webView.getSettings().setDefaultFontSize(50);
        // 支持手势焦点
        webView.requestFocusFromTouch();
        // 隐藏滚动条
        webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
        // 支持插件
        // webView.getSettings().setPluginsEnabled(true);

        // 设置缓冲大小,我设的是8M
        webView.getSettings().setAppCacheMaxSize(1024 * 1024 * 8);
        String appCacheDir = this.getApplicationContext()
                .getDir("cache", Context.MODE_PRIVATE).getPath();
        webView.getSettings().setAppCachePath(appCacheDir);
        webView.getSettings().setAllowFileAccess(true);
        webView.getSettings().setAppCacheEnabled(true);
        webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);

        // 启用数据库
        webView.getSettings().setDatabaseEnabled(true);
        webView.getSettings().setGeolocationDatabasePath(
                context.getFilesDir().getPath());
        // 启用地理定位
        webView.getSettings().setGeolocationEnabled(true);
        // 设置定位的数据库路径
        // 设置可以使用localStorage
        webView.getSettings().setDomStorageEnabled(true);
        webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);

        // 设置setWebChromeClient对象
        // webView.setWebChromeClient(new WebChromeClientLocal());
        // 设置webview为一个单独的client, 这样可以使加载url不调用系统的browser
        webView.setWebViewClient(new WebViewClient() {

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }

            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                // TODO Auto-generated method stub
                super.onPageStarted(view, url, favicon);
            }

        });

        // webView的下载监听器
        webView.setDownloadListener(new MyWebViewDownLoadListener());

    }

    public class WebChromeClientLocal extends WebChromeClient {
        // 进度条
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (newProgress == 100) {
                ProgressWebView.progressbar.setVisibility(View.GONE);
            } else {
                if (ProgressWebView.progressbar.getVisibility() == View.GONE)
                    ProgressWebView.progressbar.setVisibility(View.VISIBLE);
                ProgressWebView.progressbar.setProgress(newProgress);
            }
            super.onProgressChanged(view, newProgress);
            // WebBaseActivity.this.setProgress(newProgress * 100);
        }

        @Override
        public boolean onCreateWindow(WebView view, boolean dialog,
                boolean userGesture, Message resultMsg) {
            WebView childView = new WebView(context);
            final WebSettings settings = childView.getSettings();
            settings.setUseWideViewPort(true);
            settings.setLoadWithOverviewMode(true);

            // 两手滑动指放缩功能
            settings.setSupportZoom(true);
            settings.setBuiltInZoomControls(true);

            // 支持多窗口
            settings.setSupportMultipleWindows(true);
            settings.setJavaScriptEnabled(true);
            // 电脑上的浏览器,例如IE,你在A打开B后,A是还会存在的,也就存在了2个窗口。
            childView.setWebChromeClient(this);
            WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
            transport.setWebView(childView);
            resultMsg.sendToTarget();
            return true;
        }
    }

    /**
     * 下载
     */
    private class MyWebViewDownLoadListener implements DownloadListener {
        
        @Override
        public void onDownloadStart(String url, String userAgent,
                String contentDisposition, String mimetype, long contentLength) {
            // Uri uri = Uri.parse(url);
            // Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            // startActivity(intent);
            // Log.i("MyWebViewDownLoadListener", "************");
            // downloadFile("http://124.160.11.208:8084/wap/upload/knowledgeBase/excel.xlsx");

        }

    }

    /**
     * 判断文件后缀
     *
     * @param File
     *            文件
     * @return String 返回文件后缀
     */
    private String getMIMEType(File file) {

        String type = "*/*";
        String fName = file.getName();
        // 获取后缀名前的分隔符"."在fName中的位置。
        int dotIndex = fName.lastIndexOf(".");
        if (dotIndex < 0) {
            return type;
        }
        /* 获取文件的后缀名 */
        String end = fName.substring(dotIndex, fName.length()).toLowerCase();
        if (end == "") {
            return type;
        }
        // 与.xls或者.xlsx匹配的MIME类型。
        for (int i = 0; i < MIME_table.length; i++) {
            if (end.equals(MIME_table[i][0]))
                type = MIME_table[i][1];
        }
        return type;
    }

    /**
     * 打开文件
     *
     * @param file
     *            文件
     */
    private void openFile(File file) {
        Intent intent = new Intent("android.intent.action.VIEW");
        intent.addCategory("android.intent.category.DEFAULT");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        Uri uri = Uri.fromFile(file);
        intent.setDataAndType(uri, getMIMEType(file));
        String end = "";
        for (int i = 0; i < MIME_table.length; i++) {
            if (getMIMEType(file).equals(MIME_table[i][1]))
                end = MIME_table[i][0];
        }
        try {
            startActivity(intent);
        } catch (ActivityNotFoundException e) {
            AlertDialog.Builder builder = new AlertDialog.Builder(
                    WebBaseActivity.this);
            builder.setTitle("提示");
            builder.setMessage("请安装能打开以\"" + end + "\"为后缀名的相应办公软件");
            builder.setPositiveButton("确定",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            // TODO Auto-generated method stub
                            // finish();
                        }
                    }).show();
        }

    }

    /**
     * 从服务器下载文件
     *
     * @param url
     */
    @SuppressWarnings("unused")
    private void downloadFile(final String url) {
        // 进度条对话框
        final ProgressDialog pd;
        pd = new ProgressDialog(this);
        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pd.setMessage("下载");
        pd.show();
        new Thread() {
            @Override
            public void run() {
                Looper.prepare();
                try {
                    File file = getFileFromServer(url, pd);

                    if (file == null) {
                        pd.dismiss();
                        AlertDialog.Builder builder = new AlertDialog.Builder(
                                context);
                        builder.setTitle("提示");
                        builder.setMessage("SD卡未插入或SD卡容量不足");
                        builder.setPositiveButton("确定",
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog,
                                            int which) {
                                        // TODO Auto-generated method stub
                                        finish();
                                    }
                                }).show();

                    } else {
                        // 启动Intent
                        openFile(file);
                        // file.delete();
                        // 结束掉进度条对话框
                        pd.dismiss();
                    }
                } catch (Exception e) {
                    // 下载文件失败
                    AlertDialog.Builder builder = new AlertDialog.Builder(
                            context);
                    builder.setTitle("提示");
                    builder.setMessage("下载失败,请检查SD卡是否插入");
                    builder.setPositiveButton("确定",
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog,
                                        int which) {
                                    // TODO Auto-generated method stub
                                    finish();
                                }
                            }).show();
                    pd.dismiss();
                }
                Looper.loop();
            }
        }.start();
    }

    /**
     * 下载文件的详细判断
     *
     * @param urlStr
     * @param pd
     *            dialog
     * @return File
     * @throws Exception
     */
    @SuppressWarnings({ "unused", "deprecation" })
    private File getFileFromServer(String urlStr, ProgressDialog pd)
            throws Exception {
        // 如果相等的话表示当前的sdcard挂载在手机上并且是可用的
        String SDCardRoot = Environment.getExternalStorageDirectory()
                .getAbsolutePath() + File.separator;
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            // 判断sd卡可用内存大小
            StatFs statfs = new StatFs(Environment
                    .getExternalStorageDirectory().getPath());
            long blocSize = statfs.getBlockSize();
            long availaBlock = statfs.getAvailableBlocks();
            long availaSpace = blocSize * availaBlock;
            if (availaSpace >= conn.getContentLength()) {
                // 获取到文件的大小
                pd.setMax(conn.getContentLength());
                InputStream is = conn.getInputStream();

                // File tmpFile = new File(SDCardRoot + "ZJDownload");
                // if (!tmpFile.exists()) {
                // tmpFile.mkdir();
                // }
                File file = null;
                String type = urlStr.substring(urlStr.lastIndexOf("."));
                // Log.i("type", type+"*************");
                file = new File(FileUtils.getCacheImagePath() + "/details."
                        + type);

                FileOutputStream fos = new FileOutputStream(file);
                BufferedInputStream bis = new BufferedInputStream(is);
                byte[] buffer = new byte[1024];
                int len;
                int total = 0;
                while ((len = bis.read(buffer)) != -1) {
                    fos.write(buffer, 0, len);
                    total += len;
                    // 获取当前下载量
                    pd.setProgress(total);
                }
                fos.close();
                bis.close();
                is.close();
                return file;
            } else {
                return null;
            }
        } else {
            return null;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if (webView == null) {
            return true;
        }
        // 按下BACK键回到历史页面中
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            if (webView.canGoBack()) {
                webView.goBack();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值