Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Android to integrate Tencent X5 to realize document browsing function

2025-01-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces how to use Android to integrate Tencent X5 to achieve document browsing function, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, let the editor take you to know it.

Download Tencent X5 kernel

1. Go to https://x5.tencent.com/ to download the kernel of Android. The new version of Tencent X5 can integrate api 'com.tencent.tbs.tbssdk:sdk:43697', directly into bulid.gradle. If you integrate it in App, you can replace api with implementation.

Import 2.AndroidStudio into Tencent X5

a. Import the downloaded jar package into libs, then run as, and then import jnilibs into main package.

B. Module build.gradle add cpu adaptation

Initialize Tencent X5 in 3.Application and call the init method in the onCreate () method

QbSdk.initX5Environment (this, new QbSdk.PreInitCallback () {@ Override public void onCoreInitFinished () {} @ Override public void onViewInitFinished (boolean b) {Log.e ("xxx", "hasLoad" + b); / / the state of successful kernel loading is saved locally, and the SharePreference utility class can be replaced with its own SharedPreferenceUtils.saveBoolean (getApplicationContext (), "hasLoad", b);}})

4. Calls within the application, regardless of whether the kernel is loaded or not, download the online documents locally and open them. The difference is that the unloaded kernel will use QQ Browser or other App's file browsing function similar to Wechat (this call is automatically handled by Tencent X5, so we don't need to care), while after loading the kernel, use X5's TbsReaderView to open the file, followed by the specific code.

Integration of Retrofit,RxJava and progress manager ProgressManager in a.bulid.gradle

Implementation 'io.reactivex:rxandroid:1.2.1' implementation' com.squareup.retrofit2:converter-gson:2.3.0' implementation 'com.squareup.retrofit2:adapter-rxjava:2.1.0' implementation' com.squareup.retrofit2:retrofit:2.3.0' implementation 'io.reactivex:rxjava:1.2.6' implementation' me.jessyan:progressmanager:1.5.0'

Write network download tool

Public interface LoadFileApi {@ GET Call loadPdfFile (@ Url String fileUrl);} public class LoadFileModel {/ / use this method to download the file public static void loadPdfFile (String url, Callback callback) {Retrofit retrofit = new Retrofit.Builder () .baseUrl ("https://www.baidu.com/") .client (ProgressManager.getInstance (). With (new OkHttpClient.Builder ()) .build ()) .addConverterFactory (GsonConverterFactory.create ()) .build (); LoadFileApi mLoadFileApi = retrofit.create (LoadFileApi.class) If (! TextUtils.isEmpty (url)) {Call call = mLoadFileApi.loadPdfFile (url); call.enqueue (callback);}

b. Specific call

First of all, register file progress download monitoring

Private ProgressDialog commonProgressDialog;// switches to its own progress control private ProgressInfo mLastDownloadingInfo; ProgressManager.getInstance () .addResponseListener (url, new ProgressListener () {@ Override public void onProgress (ProgressInfo progressInfo) {if (mLastDownloadingInfo = = null) {mLastDownloadingInfo = progressInfo;} / / because it takes the time at the start of the request as Id, so the higher the value, the newer the if (progressInfo.getId ()

< mLastDownloadingInfo.getId()) { return; } else if (progressInfo.getId() >

MLastDownloadingInfo.getId () {mLastDownloadingInfo = progressInfo;} int progress = mLastDownloadingInfo.getPercent (); commonProgressDialog.setProgress (progress); Log.d ("xxx", "- Download--" + progress + "%" + mLastDownloadingInfo.getSpeed () + "byte/s" + mLastDownloadingInfo.toString ()); if (mLastDownloadingInfo.isFinish ()) {/ / description that commonProgressDialog.dismiss () has been downloaded; Log.d ("xxx", "--Download-- finish") } @ Override public void onError (long id, Exception e) {e.printStackTrace (); new Handler () .post (new Runnable () {@ Override public void run () {commonProgressDialog.dismiss ();}});}});});}

Then open the file.

Private static final String DOWN_DIR = Environment.getExternalStorageDirectory () + File.separator+ "Download"; / / the path to download the file, you can customize / / open the file private void openFile (String filePath,String fileName) {boolean hasLoad = SharedPreferenceUtils.getBoolean (mContext, "hasLoad"); / / whether to record the kernel if (hasLoad) {/ / Activity Intent intentDoc = new Intent (this,FileDisplayActivity.class); intentDoc.putExtra ("path", filePath); intentDoc.putExtra ("fileName", fileName); startActivity (intentDoc) } else {if (! Environment.getExternalStorageState (). Equals (Environment.MEDIA_MOUNTED)) {Toast.makeText (this, "current SD unavailable", Toast.LENGTH_LONG). Show (); return;} try {File file = new File (DOWN_DIR, fileName); if (file.exists ()) {QbSdk.openFileReader (this, file.getAbsolutePath (), null, new ValueCallback () {@ Override public void onReceiveValue (String s) {Log.e ("xxx", s);}}) } else {downLoadFile (filePath,fileName);}} catch (Exception e) {e.printStackTrace (); ToastUtils.showShortToast (mContext, "already downloaded");} private void downLoadFile (final String url, final String fileName) {commonProgressDialog.show (); LoadFileModel.loadPdfFile (url, new Callback () {@ Override public void onResponse (@ NonNull Call call, @ NonNull Response response) {InputStream is = null; byte [] buf = new byte [2048]; int len; FileOutputStream fos = null Try {ResponseBody responseBody = response.body (); if (responseBody! = null) {is = responseBody.byteStream (); final File file = new File (DOWN_DIR, fileName); fos = new FileOutputStream (file); while ((len = is.read (buf)! =-1) {fos.write (buf, 0, len);} fos.flush () / / unloaded kernel calling methods QbSdk.openFileReader (mContext, file.getAbsolutePath (), null, new ValueCallback () {@ Override public void onReceiveValue (String s) {Log.e ("xxx", s);}}); ToastUtils.showLongToast (MeetingDetailActivity.this, "downloaded successfully, saved in Download folder");}} catch (Exception e) {commonProgressDialog.dismiss (); ProgressManager.getInstance () .notifyOnErorr (url,e) ToastUtils.showLongToast (MeetingDetailActivity.this, "download failed");} finally {try {if (is! = null) is.close ();} catch (IOException e) {e.printStackTrace ();} try {if (fos! = null) fos.close ();} catch (IOException e) {e.printStackTrace ();} @ Override public void onFailure (@ NonNull Call call, @ NonNull Throwable t) {t.printStackTrace (); ToastUtils.showShortToast (MeetingDetailActivity.this, "download failed") CommonProgressDialog.dismiss ();});}

FileDisplayActivity code, for some package names, you can switch to your own package name, and some third-party libraries like progress display, or you can switch to your own progress control.

Import android.content.Intent;import android.os.Bundle;import android.os.Environment;import android.os.Handler;import android.os.Message;import android.support.annotation.NonNull;import android.support.annotation.Nullable;import android.support.v7.app.AppCompatActivity;import android.text.TextUtils;import android.util.Log;import android.view.View;import android.view.WindowManager;import android.widget.TextView;import com.anshi.oatencentschool.R;import com.anshi.oatencentschool.utils.DialogBuild;import com.anshi.oatencentschool.utils.StatusBarUtils Import com.anshi.oatencentschool.utils.ToastUtils;import com.anshi.oatencentschool.utils.WeakHandler;import com.anshi.oatencentschool.utils.filetool.LoadFileModel;import com.anshi.oatencentschool.utils.filetool.SuperFileView2;import com.kaopiz.kprogresshud.KProgressHUD;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import me.jessyan.progressmanager.ProgressListener;import me.jessyan.progressmanager.ProgressManager;import me.jessyan.progressmanager.body.ProgressInfo;import okhttp3.ResponseBody;import retrofit2.Call;import retrofit2.Callback Import retrofit2.Response;public class FileDisplayActivity extends AppCompatActivity {private String TAG = "FileDisplayActivity"; / / TBS reading and browsing function provided by Tencent. Open office and pdf files private SuperFileView2 mSuperFileView; private String filePath; private TextView mTextView; private static final String DOWN_DIR = Environment.getExternalStorageDirectory () + File.separator+ "Download" without third party software; private String fileName; private KProgressHUD commonProgressDialog; private WeakHandler weakHandler = new WeakHandler (new Handler.Callback () {@ Override public boolean handleMessage (Message msg) {int progress = msg.arg1) If (progress==100) {commonProgressDialog.setProgress (progress); commonProgressDialog.dismiss ();} else {commonProgressDialog.setProgress (progress);} return true;}}); @ Override protected void onCreate (@ Nullable Bundle savedInstanceState) {super.onCreate (savedInstanceState); setContentView (R.layout.activity_file_display); getWindow (). AddFlags (WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_FULLSCREEN); commonProgressDialog = DialogBuild.getBuild (). CreateCommonProgressDialog (this, "downloading"); init () } / * initialize * / public void init () {mTextView = (TextView) findViewById (R.id.file_album_name); fileName = getIntent (). GetStringExtra ("fileName"); int lastIndexOf = fileName.lastIndexOf ("."); String substring = fileName.substring (0, lastIndexOf); mTextView.setText (substring); mSuperFileView = (SuperFileView2) findViewById (R.id.mSuperFileView); mSuperFileView.setOnGetFilePathListener (new SuperFileView2.OnGetFilePathListener () {@ Override public void onGetFilePath (SuperFileView2 mSuperFileView2) {getFilePathAndShowFile (mSuperFileView)) }}); Intent intent = this.getIntent (); String path = (String) intent.getSerializableExtra ("path"); if (! TextUtils.isEmpty (path)) {Log.d (TAG, "File path:" + path); setFilePath (path);} mSuperFileView.show (); ProgressManager.getInstance (). AddResponseListener (path, new ProgressListener () {@ Override public void onProgress (ProgressInfo progressInfo) {int percent = progressInfo.getPercent (); Message obtain = Message.obtain (); obtain.arg1 = percent; weakHandler.sendMessage (obtain) } @ Override public void onError (long id, Exception e) {}});} @ Override protected void onResume () {super.onResume (); StatusBarUtils.setWindowStatusBarColor (this,R.color.color_main) } / * display file * @ param mSuperFileView2 control * / private void getFilePathAndShowFile (SuperFileView2 mSuperFileView2) {if (getFilePath (). Contains ("http") & &! new File (DOWN_DIR, fileName). Exists () {/ / the network address should first download downLoadFile (getFilePath (), fileName,mSuperFileView2);} else {try {mSuperFileView2.displayFile (new File (DOWN_DIR, fileName));} catch (Exception e) {e.printStackTrace () } public void setFilePath (String fileUrl) {this.filePath = fileUrl;} private String getFilePath () {return filePath;} / * back the previous menu * @ param view Control * / public void onClick (View view) {finish ();} private void downLoadFile (final String url, final String fileName,final SuperFileView2 mSuperFileView2) {commonProgressDialog.show () LoadFileModel.loadPdfFile (url, new Callback () {@ Override public void onResponse (@ NonNull Call call, @ NonNull Response response) {InputStream is = null; byte [] buf = new byte [2048]; int len; FileOutputStream fos = null; try {ResponseBody responseBody = response.body (); is = responseBody.byteStream (); final File file = new File (DOWN_DIR, fileName); fos = new FileOutputStream (file); while (len = is.read (buf))! =-1) {fos.write (buf, 0, len) } fos.flush (); mSuperFileView2.displayFile (file); ToastUtils.showLongToast (FileDisplayActivity.this, "download succeeded and saved in Download folder");} catch (Exception e) {commonProgressDialog.dismiss (); ToastUtils.showLongToast (FileDisplayActivity.this, "download failed");} finally {try {if (is! = null) is.close ();} catch (IOException e) {e.printStackTrace ();} try {if (fos! = null) fos.close () } catch (IOException e) {e.printStackTrace (); @ Override public void onFailure (@ NonNull Call call, @ NonNull Throwable t) {t.printStackTrace (); ToastUtils.showShortToast (FileDisplayActivity.this, "download failed"); commonProgressDialog.dismiss ();}});}}

Layout Layout:

SuperFileView2 code, this custom class is imported from https://github.com/ZhongXiaoHong/superFileView

Import android.content.Context;import android.os.Bundle;import android.os.Environment;import android.text.TextUtils;import android.util.AttributeSet;import android.util.Log;import android.widget.FrameLayout;import android.widget.LinearLayout;import com.tencent.smtt.sdk.TbsReaderView;import java.io.File;/** Created by 12457 on 2017-8-29. * / public class SuperFileView2 extends FrameLayout {private static String TAG = "SuperFileView"; private TbsReaderView mTbsReaderView; private Context context; public SuperFileView2 (Context context) {this (context, null, 0);} public SuperFileView2 (Context context, AttributeSet attrs) {this (context, attrs, 0);} public SuperFileView2 (Context context, AttributeSet attrs, int defStyleAttr) {super (context, attrs, defStyleAttr); mTbsReaderView = new TbsReaderView (context, new TbsReaderView.ReaderCallback () {@ Override public void onCallBackAction (Integer integer, Object o, Object o1) {}}) This.addView (mTbsReaderView, new LinearLayout.LayoutParams (- 1,-1)); this.context = context;} private OnGetFilePathListener mOnGetFilePathListener; public void setOnGetFilePathListener (OnGetFilePathListener mOnGetFilePathListener) {this.mOnGetFilePathListener = mOnGetFilePathListener;} private TbsReaderView getTbsReaderView (Context context) {return new TbsReaderView (context, new TbsReaderView.ReaderCallback () {@ Override public void onCallBackAction (Integer integer, Object o, Object o1) {}}) } public void displayFile (File mFile) {if (mFile! = null & &! TextUtils.isEmpty (mFile.toString () {/ / add the following sentence to solve the problem that loading files failed due to the absence of a TbsReaderTemp folder String bsReaderTemp = Environment.getExternalStorageDirectory () + File.separator+ "TbsReaderTemp"; File bsReaderTempFile = new File (bsReaderTemp); if (! bsReaderTempFile.exists ()) {Log.d ("xxx", "ready to create / storageCharacteratedUniverse TbsReaderTemptive!") ; boolean mkdir = bsReaderTempFile.mkdir (); if (! mkdir) {Log.d ("xxx", "creation / storage/emulated/0/TbsReaderTemp failed!") ;}} / / load file Bundle localBundle = new Bundle (); Log.d ("xxx", mFile.toString ()); localBundle.putString ("filePath", mFile.toString ()); localBundle.putString ("tempPath", bsReaderTemp); if (mTbsReaderView = = null) {mTbsReaderView = getTbsReaderView (context.getApplicationContext ()); String fileType = getFileType (mFile.toString ()); boolean bool = mTbsReaderView.preOpen (fileType,false); if (bool) {try {mTbsReaderView.openFile (localBundle);} catch (Exception) {e.printStackTrace () } else {String fileType = getFileType (mFile.toString ()); boolean bool = mTbsReaderView.preOpen (fileType,false); if (bool) {try {mTbsReaderView.openFile (localBundle);} catch (Exception e) {e.printStackTrace ();} else {Log.d ("xxx", "invalid file path!") ;}} / * get file type * * @ param paramString * @ return * / private String getFileType (String paramString) {String str = ""; if (TextUtils.isEmpty (paramString)) {Log.d (TAG, "paramString---- > null"); return str;} Log.d (TAG, "paramString:" + paramString); int I = paramString.lastIndexOf ('.'); if (I)

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report