Android app內(nèi)實現(xiàn)查看文檔功能

在app內(nèi)部實現(xiàn)文檔的預(yù)覽效果

通過騰訊的TbsReaderView控件實現(xiàn)文檔預(yù)覽功能,參考來源:http://www.itdecent.cn/p/84784cf428c9

一、下載騰訊X5內(nèi)核SDK

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

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

1、添加jar包


添加jar包.png

2、添加.so文件


添加.so文件.png

三、清單文件中添加權(quán)限

<uses-permission android:name="android.permission.INTERNET" />
  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
  <uses-permission android:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION"/>
  <uses-permission android:name="android.permission.ACCESS_DOWNLOAD_MANAGER"/>
  <uses-permission android:name="android.permission.WRITE_SETTINGS"/>
  <uses-permission android:name="android.permission.READ_PHONE_STATE"/>

四、app內(nèi)顯示文檔

該插件只支持展示本地文檔,不支持在線預(yù)覽功能,所以,要先下載文檔保存的本地,然后打開文檔

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<Boolean>() {
                    @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, "未授予讀寫權(quán)限,無法查看", 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()) {
                //已經(jīng)下載的字節(jié)數(shù)
                int currentBytes = cursor.getInt(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
                //總需下載的字節(jié)數(shù)
                int totalBytes = cursor.getInt(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
                //狀態(tài)所在的列索引
                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進行網(wǎng)絡(luò)請求時,如果URL中含有中文,需要進行URL轉(zhuǎn)碼

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

2、讀寫權(quán)限問題

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,058評論 25 709
  • 最基礎(chǔ)的使用方法 最簡單的布局: 在Activity中使用WebView: 但只是這樣的話,在模擬器上是會直接調(diào)到...
    HolenZhou閱讀 7,947評論 12 33
  • 曾幾何時我們不知道前進路的方向,曾幾何時我們不知道迷失了自己,曾幾何時我們變得煩躁不安,開始擔(dān)心自己的未來。但今天...
    單車旅途閱讀 258評論 0 0
  • 1、 傍晚,爺爺和奶奶帶著孫子到郊野公園散步,這里空氣新鮮,小草茵茵,樹木茂盛,花團錦簇。奶奶說:“這美麗的景色讓...
    楊琴金山閱讀 301評論 0 5
  • 韓少功的筆下有個男孩,什么話都不會說,只會吐一個字——爸,爸,爸。前段時間,我聽叔叔講,我們鄰鎮(zhèn)上有個傻子,一天什...
    麻臉樹閱讀 563評論 0 2

友情鏈接更多精彩內(nèi)容