TbsForOffice
Introduction: 文档在线或者本地预览,应用内打开 Office(Word,PPT,PDF,Excel)文件,基于腾讯 X5 浏览服务
Tags:
腾讯 TBS 浏览服务应用内打开 Office(Word,PPT,PDF)文件
前言
众所周知利用 Android 系统的 Webview 是无法直接加载 Office 文件的,但是 IOS 可以,也是无奈呀! 不过还好鹅厂给我们提供了 X5 浏览器,一般来说 Android 客户端想要加载文件,一般可有三种方案:
- 由后台开发人员把 Office 文件转换成 Html 文件
- 调用手机的第三方浏览器打开
- 利用 X5 浏览器在应用内打开
图例
文件下载(OKhttp)
private void downLoadFile(){
Observable.create(new ObservableOnSubscribe<FileVo>() {
@Override
public void subscribe(final ObservableEmitter<FileVo> e) throws Exception {
final FileVo fileVo=new FileVo();
String path= FileUtil.getCachePath(TbsReaderActivity.this);
downloadUtil.download(officeUrl, path,
officeSaveName,
new DownloadUtil.OnDownloadListener() {
@Override
public void onDownloadSuccess(File file) {
fileVo.setFile(file);
e.onNext(fileVo);
e.onComplete();
}
@Override
public void onDownloading(int progress) {
showProgress(progress);
}
@Override
public void onDownloadFailed(Exception e) {
}
});
}
}).compose(RxUtils.schedulersTransformer()).subscribe(new Consumer<FileVo>() {
@Override
public void accept(FileVo fileVo) {
showOffice(fileVo);
}
});
}
文件加载
private void showOffice(FileVo fileVo){
progressBar.setProgress(fileVo.getProgress());
file=fileVo.getFile();
String bsReaderTemp = tbsReaderTemp;
File bsReaderTempFile =new File(bsReaderTemp);
if (!bsReaderTempFile.exists()) {
boolean mkdir = bsReaderTempFile.mkdir();
if(!mkdir){
Log.d("print","创建/TbsReaderTemp 失败!!!!!");
}
}
//加载文件
Bundle localBundle = new Bundle();
localBundle.putString("filePath", file.toString());
localBundle.putString("tempPath",
tbsReaderTemp);
if (tbsReaderView == null){
tbsReaderView = getTbsView();
}
boolean result = tbsReaderView.preOpen(FileUtil.getFileType(file.toString()), false);
if (result) {
tbsReaderView.openFile(localBundle);
}
}
遇到的问题
- 加载 TbsReaderView 的容器最好不要是 LinearLayoutCompat,LinearLayout 在滑动的时候会出现显示不全的情况。用 FrameLayout 较好 (目前还不清楚原因,估计是 X5 的内核机制导致)
- X5 浏览器记得需要在 Application 中进行初始化
- TbsReaderView 不能放在 layout 布局文件中,因为源码中只有 TbsReaderView(Context var1, TbsReaderView.ReaderCallback var2) {}这一个构造方法进行初始化
- 只能加载本地的文件,因此先下载到 sd 卡中再进行加载
需要在 onDestroy 中停用 TbsReaderView:tbsReaderView.onStop();
PS:如果本文对你有帮助请点个 star 或者 Fork,如有问题可在 Issues 中进行讨论