项目中需要下载文件并打开它,使用了两种方法,一种是下载下来文件后在通过intent打开,一种是利用webview来展示。
第一种:
/** * 下载文件线程 */ private class downloadApkThread extends Thread { @Override public void run() { try { // 判断SD卡是否存在,并且是否具有读写权限 if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { // 获得存储卡的路径 String sdpath = Environment.getExternalStorageDirectory() + "/"; //随便加你的文件夹的名字 mSavePath = sdpath + "wenjianbao"; URL url = new URL(fileUrl); // 创建连接 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.connect(); // 获取文件大小 int length = conn.getContentLength(); // 创建输入流 InputStream is = conn.getInputStream(); File file = new File(mSavePath); // 判断文件目录是否存在 if (!file.exists()) { file.mkdir(); } aFile = new File(mSavePath, filename); FileOutputStream fos = new FileOutputStream(aFile); int count = 0; // 缓存 byte buf[] = new byte[1024]; // 写入到文件中 do { int numread = is.read(buf); count += numread; // 计算进度条位置 progress = (int) (((float) count / length) * 100); // 更新进度 mHandler.sendEmptyMessage(DOWNLOAD); if (numread <= 0) { // 下载完成 mHandler.sendEmptyMessage(DOWNLOAD_FINISH); break; } // 写入文件 fos.write(buf, 0, numread); } while (!cancelUpdate);// 点击取消就停止下载. fos.close(); is.close(); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // 取消下载对话框显示 mDownloadDialog.dismiss(); } }; /** * 打开 * @param file */ private void openFile(File file) { // TODO Auto-generated method stub Intent i = new Intent(Intent.ACTION_VIEW); i.addCategory(Intent.CATEGORY_DEFAULT); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK ); Uri uri = Uri.fromFile(file); i.setDataAndType(uri, "application/*"); mContext.startActivity(i); }第二种就是利用webview,会用webview就可以;
WebSettings webSettings = web .getSettings(); webSettings.setUseWideViewPort(true);//设置此属性,可任意比例缩放 webSettings.setLoadWithOverviewMode(true); //使页面支持缩放 webSettings.setJavaScriptEnabled(true); webSettings.setBuiltInZoomControls(true); webSettings.setSupportZoom(true); web.loadUrl(WEBURL);