Android app内实现查看文档功能

在app内部实现文档的预览效果

通过腾讯的TbsReaderView控件实现文档预览功能,参考来源:https://www.jianshu.com/p/84784cf428c9

一、下载腾讯X5内核SDK

http://x5.tencent.com/tbs/sdk.html

二、项目中添加jar包和.so文

1、添加jar包


添加jar包.png

2、添加.so文件


添加.so文件.png

三、清单文件中添加权限


  
  
  
  
  

四、app内显示文档

该插件只支持展示本地文档,不支持在线预览功能,所以,要先下载文档保存的本地,然后打开文档

public class OpenReadOffice extends Activity implements TbsReaderView.ReaderCallback {
    private TbsReaderView mTbsReaderView;
    private Button mDownloadBtn;
    private DownloadManager mDownloadManager;
    private long mRequestId;
    private DownloadObserver mDownloadObserver;
    private String mFileUrl="http://www.hrssgz.gov.cn/bgxz/sydwrybgxz/201101/P020110110748901718161.doc";
    private String mFileName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.read_office);
        mTbsReaderView = new TbsReaderView(OfficeReader.this, this);
        mDownloadBtn = (Button) findViewById(R.id.btn_download);
        LinearLayout rootRl = (LinearLayout) findViewById(R.id.read_office_tbs);
        rootRl.addView(mTbsReaderView, new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));

        mFileName = parseName(mFileUrl);
        if (isLocalExist()) {
            mDownloadBtn.setVisibility(View.GONE);
            displayFile();
        } else {
            startDownload();
        }
    }

    public void onClickDownload(View v) {
        if (isLocalExist()) {
            mDownloadBtn.setVisibility(View.GONE);
            displayFile();
        } else {
            startDownload();
        }
    }

    private void displayFile() {
           Bundle bundle = new Bundle();
           bundle.putString("filePath", getLocalFile().getPath());
           bundle.putString("tempPath", Environment.getExternalStorageDirectory().getPath());
           boolean result = mTbsReaderView.preOpen(parseFormat(mFileName), false);
             if (result) {
                  mTbsReaderView.openFile(bundle);
                }
    }

    private String parseFormat(String fileName) {
        return fileName.substring(fileName.lastIndexOf(".") + 1);
    }

    private String parseName(String url) {
        String fileName = null;
        try {
            fileName = url.substring(url.lastIndexOf("/") + 1);
        } finally {
            if (TextUtils.isEmpty(fileName)) {
                fileName = String.valueOf(System.currentTimeMillis());
            }
        }
        return fileName;
    }

    private boolean isLocalExist() {
        return getLocalFile().exists();
    }

    private File getLocalFile() {
        return new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), mFileName);
    }

    private void startDownload() {
        Toast.makeText(this, "开始下载文件", Toast.LENGTH_SHORT).show();
        RxPermissions.getInstance(this)
                .request(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(new Action1() {
                    @Override
                    public void call(Boolean aBoolean) {
                        if (aBoolean) {
                            mDownloadObserver = new DownloadObserver(new Handler());
                            getContentResolver().registerContentObserver(Uri.parse("content://downloads/my_downloads"), true, mDownloadObserver);

                            mDownloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
                            //mFileUrl = Uri.encode(mFileUrl, "-![.:/,%?&=]");
                            DownloadManager.Request request = new DownloadManager.Request(Uri.parse(mFileUrl));
                            request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, mFileName);
                            request.allowScanningByMediaScanner();
//                            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN);
                            mRequestId = mDownloadManager.enqueue(request);

                        } else {
                            //不同意
                            Toast.makeText(OfficeReader.this, "未授予读写权限,无法查看", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    private void queryDownloadStatus() {
        DownloadManager.Query query = new DownloadManager.Query().setFilterById(mRequestId);
        Cursor cursor = null;
        try {
            cursor = mDownloadManager.query(query);
            if (cursor != null && cursor.moveToFirst()) {
                //已经下载的字节数
                int currentBytes = cursor.getInt(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
                //总需下载的字节数
                int totalBytes = cursor.getInt(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
                //状态所在的列索引
                int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
                Log.i("downloadUpdate: ", currentBytes + " " + totalBytes + " " + status);
                mDownloadBtn.setText("正在下载:" + currentBytes + "/" + totalBytes);
                if (DownloadManager.STATUS_SUCCESSFUL == status && mDownloadBtn.getVisibility() == View.VISIBLE) {
                    mDownloadBtn.setVisibility(View.GONE);
                    mDownloadBtn.performClick();
                }
            }
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    }

    @Override
    public void onCallBackAction(Integer integer, Object o, Object o1) {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mTbsReaderView.onStop();
        if (mDownloadObserver != null) {
            getContentResolver().unregisterContentObserver(mDownloadObserver);
        }
    }

    private class DownloadObserver extends ContentObserver {

        private DownloadObserver(Handler handler) {
            super(handler);
        }

        @Override
        public void onChange(boolean selfChange, Uri uri) {
            Log.i("downloadUpdate: ", "onChange(boolean selfChange, Uri uri)");
            queryDownloadStatus();
        }
    }
·
}

五、遇到的问题

1、请求地址问题
通过DownloadManager进行网络请求时,如果URL中含有中文,需要进行URL转码

mFileUrl = Uri.encode(mFileUrl, "-![.:/,%?&=]");

2、读写权限问题

你可能感兴趣的:(Android app内实现查看文档功能)