android打开pdf文件

本文介绍两种在Android中打开PDF和DOC文件的方法。一种是使用Intent直接打开,另一种是利用腾讯X5内核提供的TbsReaderView组件进行文档阅读。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我们在工作中肯定有需要,加载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/59c64f59f265da06456d7d6a

接入可以看官方的文档:https://x5.tencent.com/tbs/guide/sdkInit.html

1.先创建一个:activity_pdf的布局文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <RelativeLayout
        android:id="@+id/tb"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>


</LinearLayout>
复制代码

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();复制代码


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值