Android实践:查看远程文档
需求:APP应用中网页打开远程文档,如.pdf,.doc,.xlsx等
方案:
1.下载文件到本地
2.使用三方app打开文件
实现:
1.下载
compile 'com.loopj.android:android-async-http:1.4.11'
public void download(Context context,String url,String dirPath,String fileName){AsyncHttpClient client =new AsyncHttpClient();AsyncDownload asyncDownload = new AsyncDownload();asyncDownload.setAsyncHttpClient(client);asyncDownload.setFileName(dirPath + fileName);File file = new File(dirPath, fileName);
RangeFileAsyncHttpResponseHandler fileAsyncHttpResponseHandler = new RangeFileAsyncHttpResponseHandler(file) {@Overridepublic void onFailure(int statusCode, cz.msebera.android.httpclient.Header[] headers, Throwable throwable, File file) {}@Overridepublic void onSuccess(int statusCode, cz.msebera.android.httpclient.Header[] headers, File file) {}@Overridepublic void onCancel() {super.onCancel();}@Overridepublic void onProgress(long bytesWritten, long totalSize) {super.onProgress(bytesWritten, totalSize);}@Overridepublic void onStart() {super.onStart();}};fileAsyncHttpResponseHandler.setUseSynchronousMode(false);client.setEnableRedirects(true);//同意反复下载client.get(context, url, fileAsyncHttpResponseHandler);
}
2.打开
public void open(Context context, String docUrl){try {Uri uri = FileProvider.getUriForFile(context, context.getPackageName() + ".fileProvider", new File(docUrl));Intent intent = new Intent(Intent.ACTION_VIEW);String mimeType = getMimeTypeFromExtension(Uri.parse(docUrl).getLastPathSegment());if (TextUtils.isEmpty(mimeType)) {intent.setData(uri);} else {intent.setDataAndType(uri, mimeType);}intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);context.startActivity(Intent.createChooser(intent,"请选择应用打开"));} catch (Exception e) {e.printStackTrace();}
}public String getMimeTypeFromExtension(String fileName) {String extension = fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase();switch (extension) {case "doc":return "application/msword";case "docx":return "application/vnd.openxmlformats-officedocument.wordprocessingml.document";case "xls":return "application/vnd.ms-excel";case "xlsx":return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";case "ppt":case "pps":return "application/vnd.ms-powerpoint";case "pptx":return "application/vnd.openxmlformats-officedocument.presentationml.presentation";case "wps":return "application/vnd.ms-works";case "msg":return "application/vnd.ms-outlook";case "mpc":return "application/vnd.mpohun.certificate";case "jar":return "application/java-archive";case "tar":return "application/x-tar";case "tgz":return "application/x-compressed";case "zip":return "application/x-zip-compressed";case "txt":return "text/plain";case "jpg":case "jpeg":return "image/jpeg";case "png":return "image/png";case "gif":return "image/gif";case "mp3":return "audio/*";case "mp4":return "video/mp4";case "rmvb":return "audio/x-pn-realaudio";case "wav":case "wma":case "wmv":return "audio/*";default:return "";}}