首页 » Android » Android使用TBS浏览器加载pdf等文件

Android使用TBS浏览器加载pdf等文件

原文 http://blog.csdn.net/qingfeng812/article/details/79077350

2018-01-17 02:01:15阅读(489)

项目结构

<a href=Android使用TBS浏览器加载pdf文件" src="http://upload-images.jianshu.io/upload_images/1131704-0a8eb61b4f8b56c6.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="Android配置TBS服务" title="">

技术方案 TBS的其它优点,可以自行搜索网上其它资料,很多。 加载文件核心类是 TbsReaderView,腾讯文档没有写,所以需要查找网上资料。 TBS目前只支持加载本地文件。所以远程文件需要先下载,后用TBS加载文件显示。 负责加载和显示文件的界面,离开本界面之后务必需要销毁,否则再次加载文件无法加载成功,会一直显示加载文件进度条。

关键代码:

mTbsReaderView.onStop();//销毁界面的时候一定要加上,否则后面加载文件会发生异常。

完整项目源码
package com.yifeng.sample.tbs;
    import android.app.DownloadManager;
    import android.app.DownloadManager.Request;
    import android.content.Intent;
    import android.database.ContentObserver;
    import android.database.Cursor;
    import android.net.Uri;
    import android.os.Bundle;
    import android.os.Environment;
    import android.os.Handler;
    import android.support.v7.app.AppCompatActivity;
    import android.text.TextUtils;
    import android.util.Log;
    import android.view.View;
    import android.view.ViewGroup.LayoutParams;
    import android.widget.Button;
    import android.widget.RelativeLayout;
    import com.tencent.smtt.sdk.TbsReaderView;
    import com.tencent.smtt.sdk.TbsReaderView.ReaderCallback;
    import java.io.File;
    public class MainActivity extends AppCompatActivity implements ReaderCallback {
      private TbsReaderView mTbsReaderView;
      private Button mDownloadBtn;
      private DownloadManager mDownloadManager;
      private long mRequestId;
      private DownloadObserver mDownloadObserver;
      private String mFileUrl = "http://www.beijing.gov.cn/zhuanti/ggfw/htsfwbxzzt/shxfl/fw/P020150720516332194302.doc";
      private String mFileName;
      @Override
      protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mTbsReaderView = new TbsReaderView(this, this);
        mDownloadBtn = (Button) findViewById(R.id.btn_download);
        RelativeLayout rootRl = (RelativeLayout) findViewById(R.id.rl_root);
        rootRl.addView(mTbsReaderView, new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
        mFileName = parseName(mFileUrl);
        if (isLocalExist()) {
          mDownloadBtn.setText("打开文件");
        }
        if (isLocalExist()) {
          mDownloadBtn.setVisibility(View.GONE);
          displayFile();
        } else {
          startDownload();
        }
      }
      @Override
      public void onBackPressed() {
        startActivity(new Intent(MainActivity.this,IndexActivity.class));
        finish();//不关掉此界面,之后加载文件会无法加载
      }
      public void onClickDownload(View v) {
    //    if (isLocalExist()) {
    //      mDownloadBtn.setVisibility(View.GONE);
    //      displayFile();
    //    } else {
    //      startDownload();
    //    }
      }
      private void displayFile() {
        Bundle bundle = new Bundle();
        bundle.putString("filePath", "/storage/emulated/0/uu/HTTP权威指南.pdf");
        bundle.putString("tempPath", Environment.getExternalStorageDirectory().getPath());
        boolean result = mTbsReaderView.preOpen(parseFormat("HTTP权威指南.pdf"), 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() {
        mDownloadObserver = new DownloadObserver(new Handler());
        getContentResolver().registerContentObserver(Uri.parse("content://downloads/my_downloads"), true, mDownloadObserver);
        mDownloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(mFileUrl));
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, mFileName);
        request.allowScanningByMediaScanner();
        request.setNotificationVisibility(Request.VISIBILITY_HIDDEN);
        mRequestId = mDownloadManager.enqueue(request);
      }
      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();
        }
      }
    }

最新发布

CentOS专题

关于本站

5ibc.net旗下博客站精品博文小部分原创、大部分从互联网收集整理。尊重作者版权、传播精品博文,让更多编程爱好者知晓!

小提示

按 Ctrl+D 键,
把本文加入收藏夹