1.集成腾讯TBS
使用腾讯TBS来预览pdf,word,excel,ppt等多种类型的文件,去 腾讯浏览服务官网下载SDK,按照官方文档文档集成SDK。
2.使用TbsReaderView来加载文件
动态创建TbsReaderView,然后添加到布局中。
@Override
public boolean requestLocalData() {
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);
//把tbsReaderView添加在标题控件下面
layout.addView(tbsReaderView, 1, params);
//文件地址
String downloadUrl = getIntent().getStringExtra("downloadUrl");
//文件名
String fileName = TextUtils.isEmpty(downloadUrl) ? "" : downloadUrl.substring(downloadUrl.lastIndexOf("/") + 1);
//判断缓存中是否存在这个文件
File cacheFile = new File(StorageUtils.getCacheDirectory(this), fileName);
if (cacheFile.exists()) {
displayFile(cacheFile.getPath(), fileName);
} else {
//判断该文件是否已经下载
File downloadFile = new File(Environment.getExternalStorageDirectory(), Environment.DIRECTORY_DOWNLOADS + File.separator + fileName);
if (downloadFile.exists()) {
displayFile(downloadFile.getPath(), fileName);
} else {
//下载文件(文件下载的方法自行添加,下载完成后加载文件,此处省略)
File saveFile;
if (isDownload) {
saveFile = new File(Environment.getExternalStorageDirectory(), Environment.DIRECTORY_DOWNLOADS + File.separator + fileName);
} else {
saveFile = new File(StorageUtils.getCacheDirectory(this), fileName);
}
fileDownloader.downloadFile(downloadUrl, saveFile, this);
}
}
}
//加载文件
private void displayFile(String filePath, String fileName) {
//增加下面一句解决没有TbsReaderTemp文件夹存在导致加载文件失败
String bsReaderTemp = tbsReaderTemp;
File bsReaderTempFile =new File(bsReaderTemp);
if (!bsReaderTempFile.exists()) {
Log.d("print","准备创建/TbsReaderTemp!!");
boolean mkdir = bsReaderTempFile.mkdir();
if(!mkdir){
Log.d("print","创建/TbsReaderTemp失败!!!!!");
}
}
Bundle bundle = new Bundle();
bundle.putString("filePath", filePath);
bundle.putString("tempPath", tbsReaderTemp);
boolean result = tbsReaderView.preOpen(getFileType(fileName), false);
Log.d("print","查看文档---"+result);
if (result) {
tbsReaderView.openFile(bundle);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
//销毁界面的时候一定要加上,否则后面加载文件会发生异常。
tbsReaderView.onStop();
}
3.其他说明
1、加载文件核心类是 TbsReaderView,腾讯文档没有写,TbsReaderView建议通过动态创建,不要使用xml中引用;
2、TBS目前只支持加载本地文件。所以远程文件需要先下载,后用TBS加载文件显示;
3、加载文件的界面,离开本界面之后务必销毁TbsReaderView,否则再次加载文件无法加载成功,会一直显示加载文件进度条;代码如下:tbsReaderView.onStop();
4.腾讯TBS可以代替原生WebView,效率更高,功能更强大。
感谢大神的分享:https://blog.csdn.net/qq_31796651/article/details/100538925