Android uses TBS browser to load pdf and other files

Project structure

Technical proposal

  • Other advantages of TBS, you can search other information on the Internet, many.
  • The core class of the load file is TbsReaderView. Tencent documents are not written, so you need to find online data.
  • TBS currently only supports loading local files. Therefore, the remote file needs to be downloaded first, and then the TBS is used to load the file display.
  • The interface responsible for loading and displaying files must be destroyed after leaving this interface. Otherwise, the file cannot be loaded successfully again, and the loading file progress bar will be displayed all the time.
  • Key code:

    mTbsReaderView.onStop(); / / when destroying the interface, you must add it, otherwise an exception will occur when loading the file later.

  • Complete project source code
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("Open file");
        }

        if (isLocalExist()) {
          mDownloadBtn.setVisibility(View.GONE);
          displayFile();
        } else {
          startDownload();
        }
      }

      @Override
      public void onBackPressed() {
        startActivity(new Intent(MainActivity.this,IndexActivity.class));
        finish();//If you do not close this interface, the loading file will fail to load
      }

      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 Authoritative guide.pdf");
        bundle.putString("tempPath", Environment.getExternalStorageDirectory().getPath());
        boolean result = mTbsReaderView.preOpen(parseFormat("HTTP Authoritative guide.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()) {
            //Bytes downloaded
            int currentBytes = cursor.getInt(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
            //Total bytes to download
            int totalBytes = cursor.getInt(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
            //Column index of status
            int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
            Log.i("downloadUpdate: ", currentBytes + " " + totalBytes + " " + status);
            mDownloadBtn.setText("Downloading:" + 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();
        }
      }
    }

Tags: Android Database SDK Java

Posted on Tue, 05 May 2020 03:56:42 -0700 by cpetercarter