Android应用内展示word、excel、pdf、ppt等文件

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/haohengyuan/article/details/78046910

笔者最近两个项目里头都有需要展示文件的功能,于是做了一番调研,发现asce1885给出一份方案,不过都是关于pdf的展示:http://www.jianshu.com/p/1bf49af6584d,显然不符合笔者的要求,笔者的项目里需要展示的文件格式并不单一,后来经过一番搜索最后敲定使用腾讯的Tbs,可以在应用内打开各类型文件。不过这过程也有点坑。

什么是Tbs

腾讯浏览服务(TBS,Tencent Browsing Service)整合腾讯底层浏览技术和腾讯平台资源及能力,提供整体浏览服务解决方案。TBS更多详细的介绍,请移步:https://x5.tencent.com/tbs/

关于官网接入的坑

关于接入Tbs服务官网给出了接入文档:https://x5.tencent.com/tbs/guide/sdkInit.html,很搞笑的是我找了很久也没有发现具有打开文件能力demo工程,官网sdk里头的demo工程居然都没有展示文件功能,后来我发现官网论坛里有不少朋友留言,不知如何使用SdK打开文件,因此本文主要将的是如何使用SDK打开文件,以及对sdk打开文件的功能的简单封装。

如何接入

参考:https://x5.tencent.com/tbs/guide/sdkInit.html
1. 第一步

下载 SDK jar 包放到工程的libs目录下

image.png

  1. 第二步

x5暂时不提供64位so文件,为了保证64位手机能正常加载x5内核,进行以下两项设置:
(1)打开对应module中的build.gradle文件,在文件的android{}中的defaultConfig{}里(如果没有defaultConfig{}则手动添加)添加如下配置: ndk{abiFilters “armeabi”}

image.png
(2)添加对应目录下的liblbs.so文件

image.png

如何展示文件

显示文件关键代码,例如:

Bundle localBundle = new Bundle();
            localBundle.putString("filePath", mFile.toString());
            localBundle.putString("tempPath", Environment.getExternalStorageDirectory() + "/" + "TbsReaderTemp");
            if (this.mTbsReaderView == null)
                this.mTbsReaderView = getTbsReaderView(context);
            boolean bool = this.mTbsReaderView.preOpen(getFileType(mFile.toString()), false);
            if (bool) {
                this.mTbsReaderView.openFile(localBundle);
            }

TbsReaderView是封装的用于展示文件的View,继承与FramLayout,首先调用mTbsReaderView.preOpen(getFileType(mFile.toString()), false)进行文件打开之前的初始化工作,然后调用的mTbsReaderView.openFile(localBundle)打开文件,localBundle里包含有文件在本地的路径,加载文件步骤十分简单,其中的加载任务全部交由tbs内核完成。

简单封装

有时候可能需要加载网络文件,但是tbs目前是暂时不支持在线预览的,因此是需要使用网络将文件下载下来之后在展示,因此笔者这里对获取文件路径这一部分进行封装,如下:

 public void show() {
        if(mOnGetFilePathListener!=null){
            mOnGetFilePathListener.onGetFilePath(this);
        }
    }

    /***
     * 将获取File路径的工作,“外包”出去
     */
    public interface OnGetFilePathListener {
        void onGetFilePath(SuperFileView2 mSuperFileView2);
    }

TbsReaderView是上面的SuperFileView2的子View,完整使用如下:

 mSuperFileView = (SuperFileView2) findViewById(R.id.mSuperFileView);
        //设置获取文件路径监听
        mSuperFileView.setOnGetFilePathListener(new SuperFileView2.OnGetFilePathListener() {
            @Override
            public void onGetFilePath(SuperFileView2 mSuperFileView2) {
                getFilePathAndShowFile(mSuperFileView2);
            }
        });

        Intent intent = this.getIntent();
        String path = (String) intent.getSerializableExtra("path");
        if (!TextUtils.isEmpty(path)) {
            TLog.d(TAG, "文件path:" + path);
            setFilePath(path);
        }
        mSuperFileView.show();

效果图

展示doc文件

显示doc文件

展示Excel文件

显示Excel文件

展示pdf文件

显示pdf文件

展示ppt文件

显示ppt文件

展示txt

显示TXT文件

源码

https://github.com/ZhongXiaoHong/superFileView

猜你喜欢

转载自blog.csdn.net/haohengyuan/article/details/78046910