在做移动办公软件时,需要移动终端在线打开网页上的文档,在iPad上能直接打开文档在线显示,但是在android系统上却不能,它只是把这个文档下载下来,然后只能自己找到文档的位置点击打开,很不方便。没办法,只能自己写个客户端,拦截请求,自动下载和打开。
一:实现思路
二:核心实现
1)主要配置文件
2)核心代码
public class FileOpenTestActivity extends Activity { private WebView webView; private Context mContext = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); this.mContext = this; webView = (WebView) findViewById(R.id.webview); webView.getSettings().setJavaScriptEnabled(true); webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE); webView.setWebViewClient(new WebViewClient() { public boolean shouldOverrideUrlLoading(WebView view, String url) { //判断是否是文件下载链接,如果不是则返回,直接访问 String fileName = url.substring(url.lastIndexOf("/")); if(null == getFileType(fileName) || getFileType(fileName).equals("")){ return false; } //如果是文件下载链接,先下载,再调用系统安装的阅读器打开 try { //下载文件到SD卡 File file = downloadFile(url); //调用适合的阅读器显示文件 startActivity(getFileIntent(file)); } catch (ActivityNotFoundException e) { e.printStackTrace(); } return true; } }); webView.loadUrl("http://localhost:8888/OpenFile/fileList.html"); } /** * 下载文件 * @param fileUrl * @return */ public File downloadFile(String fileUrl) { File apkFile = null; String fileName = fileUrl.substring(fileUrl.lastIndexOf("/")); try { if (Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED)) { // 获得存储卡的路径 String sdpath = Environment.getExternalStorageDirectory() + "/"; String mSavePath = sdpath + "download"; 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(); } apkFile = new File(mSavePath, fileName); if(apkFile.exists()){ return apkFile; } FileOutputStream fos = new FileOutputStream(apkFile); int count = 0; int numread = 0; byte buf[] = new byte[1024]; while ((numread = is.read(buf)) != -1) { fos.write(buf, 0, numread); } fos.flush(); fos.close(); is.close(); } } catch (Exception e) { e.printStackTrace(); } return apkFile; } /** * 获取用于文件打开的intent * @param file * @return */ public Intent getFileIntent(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); String fileType = getFileType(file.getName()); intent.setDataAndType(uri, fileType); return intent; } /** * 从配置文件获取要下载的文件后缀和对应的MIME类型 * @param fileName * @return */ public String getFileType(String fileName){ String [] names = this.mContext.getResources().getStringArray(R.array.file_name_array); String [] types = this.mContext.getResources().getStringArray(R.array.file_type_array); for(int i=0;i<names.length;i++){ if(fileName.toLowerCase().indexOf(names[i])>=0){ return types[i]; } } return ""; } } |