我们在工作中肯定有需要,加载pdf或者doc的地方,但是,android没有提供一个好的打开方法,我又想吐槽下,人家ios可以直接打开的。。
有2钟方法打开pdf、doc。
方法一:
利用Intent打开pdf:
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.addCategory("android.intent.category.DEFAULT");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Uri uri = Uri.fromFile(file);
intent.setDataAndType(uri, "application/pdf");
startActivity(intent);复制代码
或者:Uri uri = Uri.parse(arg0);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);复制代码
方法2利用腾讯x5打开:
摘自:https://juejin.im/post/6844903497528410125
接入可以看官方的文档:https://x5.tencent.com/tbs/guide/sdkInit.html
1.先创建一个:activity_pdf的布局文件:<?xml version="1.0" encoding="utf-8"?>
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
android:id="@+id/tb"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
复制代码
2.创建的activity集成TbsReaderView.ReaderCallback接口,不用管里面的方法;
3.创建TbsReaderView的实例对象,并通过addView方法注入到RelativeLyout布局里:relayout= (RelativeLayout) findViewById(R.id.tb);
TbsReaderView mTbsReaderView=new TbsReaderView(this,this);
relayout.addView(mTbsReaderView,new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT));复制代码
4.通过Bulder把pdf的文件路径和插件缓存路径传过去,在这之前先初始化:Bundle bundle = new Bundle();
bundle.putString("filePath", FileUrl);
bundle.putString("tempPath", Environment.getExternalStorageDirectory().getPath());
File file = new File(FileUrl);
boolean result = mTbsReaderView.preOpen(parseFormat(FileUrl), false);
LogTool.ii(TAG,"result: "+result+" Path: "+file.getPath());
if (result) {
mTbsReaderView.openFile(bundle);
}
复制代码
parse方法:private String parseFormat(String fileName) {
return fileName.substring(fileName.lastIndexOf(".") + 1);
}复制代码
需要注意的一点是在onDestory方法里面需要x5释放:mTbsReaderView.onStop();复制代码