Android realizes file preview function through Tencent TBS
- 2021-12-04 11:23:41
- OfStack
1. Integrate Tencent TBS
Use Tencent TBS to preview pdf, word, excel, ppt and other types of files, download SDK from Tencent browsing service official website, and integrate SDK according to official documents.
2. Load files using TbsReaderView
TbsReaderView is created dynamically and added to the layout.
// Callback
TbsReaderView.ReaderCallback readerCallback = new TbsReaderView.ReaderCallback() {
@Override
public void onCallBackAction(Integer integer, Object o, Object o1) {
} };
tbsReaderView = new TbsReaderView(this, readerCallback);
RelativeLayout.LayoutParams params=new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT);
params.addRule(RelativeLayout.BELOW,R.id.title_layout);
// Put tbsReaderView Add under title control
layout.addView(tbsReaderView,1,params);
// File address
String filePath=getIntent().getStringExtra("filePath");
// Filename
String fileName=getIntent().getStringExtra("fileName");
// Load file
displayFile(filePath,fileName);
// Load file
private void displayFile(String filePath, String fileName) {
// Add the following 1 Has the sentence been solved TbsReaderTemp Failure to load file due to folder existence
String bsReaderTemp = tbsReaderTemp;
File bsReaderTempFile =new File(bsReaderTemp);
if (!bsReaderTempFile.exists()) {
Log.d("print"," Prepare to create /TbsReaderTemp ! ! ");
boolean mkdir = bsReaderTempFile.mkdir();
if(!mkdir){
Log.d("print"," Create /TbsReaderTemp Failure! ! ! ! ! ");
}
}
Bundle bundle = new Bundle();
bundle.putString("filePath", filePath);
bundle.putString("tempPath", tbsReaderTemp);
boolean result = tbsReaderView.preOpen(getFileType(fileName), false);
Log.d("print"," View Documents ---"+result);
if (result) {
tbsReaderView.openFile(bundle);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
// When destroying the interface, 1 Be sure to add it, otherwise an exception will occur when the file is loaded later.
tbsReaderView.onStop();
}
3. Other notes
1. The core class of loading file is TbsReaderView, and Tencent document is not written. TbsReaderView recommends dynamic creation instead of reference in xml;
2. TBS currently only supports loading local files. Therefore, remote files need to be downloaded first, and then loaded with TBS for file display;
3. The interface for loading files. After leaving this interface, you must destroy TbsReaderView, otherwise the file cannot be loaded successfully again, and the loading file progress bar will be displayed directly; The code is as follows: tbsReaderView. onStop ();
4. Tencent TBS can replace the native WebView with higher efficiency and more powerful functions.
Summarize