Android实现在线预览office文档(Word,Pdf,excel,PPT.txt等格式)

1.概述

我们都知道,Android原生并没有提供浏览office文档格式的相关Api,在安卓端想要实现在线预览office文档的功能显然很是复杂,我们手机安装QQ浏览器时,在手机打开office文档时会提示如图,
插件加载

这就是这篇文章的主角–腾讯X5内核(TBS)

2,什么是TBS

腾讯浏览服务(TBS,Tencent Browsing Service)整合腾讯底层浏览技术和腾讯平台资源及能力,提供整体浏览服务解决方案。腾讯浏览服务面向应用开发商和广大开发者,提供浏览增强,内容框架,广告体系,H5游戏分发,大数据等服务,能够帮助应用开发商大幅改善应用体验,有效提升开发,运营,商业化的效率。

我们主要介绍的是他的文件打开能力
目前支持42种文件格式,包括20种文档、12种音乐、6种图片和4种压缩包。帮助应用实现应用内文档浏览,无需跳转调用其他应用。
详细介绍见TBS官方网站

3.加载txt格式的效果图

注意加载的过程,是先加载支持txt格式的插件,然后把txt文档加载出来的

加载txt格式的效果图

4.TBS的使用预览office文件

详细的使用见官方技术文档
技术文档中并没有提供浏览文件相关的信息
核心类就一个 TbsReaderView 继承自FrameLayout

由于使用起来比较简单,我就直接贴代码了,请看注释

布局文件

<?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">

    <Button
        android:id="@+id/button"
        android:onClick="onClick"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="@color/colorAccent"
        android:text="请选择文件打开"/>

    <FrameLayout
        android:id="@+id/fl"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1">
    </FrameLayout>
</LinearLayout>

java代码实现

package com.example.x5tbsdemo;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.FrameLayout;

import com.silang.superfileview.R;
import com.tencent.smtt.sdk.TbsReaderView;

import java.io.File;


public class Main extends Activity {

    private static final int CHOOSE_REQUEST_CODE = 1000;
    private FrameLayout frameLayout;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);
        frameLayout = (FrameLayout) findViewById(R.id.fl);
    }

    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.button:
                chooseFile();
                break;
        }
    }

    //选择文件
    private void chooseFile() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*");
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        Intent chooser = Intent.createChooser(intent, "请选择要代开的文件");
        startActivityForResult(chooser, CHOOSE_REQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            if (resultCode == RESULT_OK) {
                switch (requestCode) {
                    case CHOOSE_REQUEST_CODE:
                        Uri uri = data.getData();
                        String path = getPathFromUri(this, uri);
                        openFile(path);
                        break;
                }
            }
        }
    }

    /**
     * 打开文件
     */
    private void openFile(String path) {
        TbsReaderView readerView = new TbsReaderView(this, new TbsReaderView.ReaderCallback() {
            @Override
            public void onCallBackAction(Integer integer, Object o, Object o1) {

            }
        });
        //通过bundle把文件传给x5,打开的事情交由x5处理
        Bundle bundle = new Bundle();
        //传递文件路径
        bundle.putString("filePath", path);
        //加载插件保存的路径
        bundle.putString("tempPath", Environment.getExternalStorageDirectory() + File.separator + "temp");
        //加载文件前的初始化工作,加载支持不同格式的插件
        boolean b = readerView.preOpen(getFileType(path), false);
        if (b) {
            readerView.openFile(bundle);
        }
        frameLayout.addView(readerView);
    }

    /***
     * 获取文件类型
     *
     * @param path 文件路径
     * @return 文件的格式
     */
    private String getFileType(String path) {
        String str = "";

        if (TextUtils.isEmpty(path)) {
            return str;
        }
        int i = path.lastIndexOf('.');
        if (i <= -1) {
            return str;
        }
        str = path.substring(i + 1);
        return str;
    }

    /**
     * @param context
     * @param uri     文件的uri
     * @return 文件的路径
     */
    public String getPathFromUri(final Context context, Uri uri) {
        // 选择的图片路径
        String selectPath = null;

        final String scheme = uri.getScheme();
        if (uri != null && scheme != null) {
            if (scheme.equals(ContentResolver.SCHEME_CONTENT)) {
                // content://开头的uri
                Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
                if (cursor != null && cursor.moveToFirst()) {
                    int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                    // 取出文件路径
                    selectPath = cursor.getString(columnIndex);

                    // Android 4.1 更改了SD的目录,sdcard映射到/storage/sdcard0
                    if (!selectPath.startsWith("/storage") && !selectPath.startsWith("/mnt")) {
                        // 检查是否有"/mnt"前缀
                        selectPath = "/mnt" + selectPath;
                    }
                    //关闭游标
                    cursor.close();
                }
            } else if (scheme.equals(ContentResolver.SCHEME_FILE)) {// file:///开头的uri
                // 替换file://
                selectPath = uri.toString().replace("file://", "");
                int index = selectPath.indexOf("/sdcard");
                selectPath = index == -1 ? selectPath : selectPath.substring(index);
                if (!selectPath.startsWith("/mnt")) {
                    // 加上"/mnt"头
                    selectPath = "/mnt" + selectPath;
                }
            }
        }
        return selectPath;
    }
}

清单文件要添加权限

 <uses-permission android:name="android.permission.INTERNET" />
  <uses-permission   android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
 <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Note: Tbs不支持加载网络的文件,需要先把文件下载到本地,然后再加载出来

  • 5
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 33
    评论
评论 33
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值