Android 在线预览ppt、doc、xls、txt等文件

说明:使用TBS(腾讯浏览服务)打开,目前不支持在线预览,只能先下载下来,在打开

下载SDK

第一步:

加载jar、so

tbs_sdk_thirdapp_v4.3.0.1072_43646_sharewithdownloadwithfile_withoutGame_obfs_20190429_175122.jar

第二步:

权限处理

1. 清单文件配置

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission   android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

2. 动态权限申请

private String[] permissions = new String[]{
		Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE
};

private List<String> mPermissionList = new ArrayList<>();

private void requestPermisson() {
	if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
		mPermissionList.clear();
		for (int i = 0; i < permissions.length; i++) {
			if (ContextCompat.checkSelfPermission(mContext, permissions[i]) != PackageManager.PERMISSION_GRANTED) {
				mPermissionList.add(permissions[i]);
			}
		}
		if (mPermissionList.isEmpty()) {//未授予的权限为空,表示都授予了
			hasPermissionDismiss = false;
		} else {//请求权限方法
			String[] permissionsArr = mPermissionList.toArray(new String[mPermissionList.size()]);
			requestPermissions(permissionsArr, 100);
		}
	}
}

private boolean hasPermissionDismiss = false;//用户是否禁止权限

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
	super.onRequestPermissionsResult(requestCode, permissions, grantResults);
	if (requestCode == 100 && grantResults.length > 0) {
		for (int i = 0; i < grantResults.length; i++) {
			if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
				hasPermissionDismiss = true;
				break;
			}
		}
		//如果有权限没有被允许
		if (hasPermissionDismiss) {
			showPermissionDialog();//跳转到系统设置权限页面,或者直接关闭页面,不让他继续访问
		} else {
			//X5内核的初始化
			initX5();
		}
	}
}

第三步:

x5内核初始化,权限申请之前初始化会失败,

private void initX5(){
	QbSdk.initX5Environment(this, new QbSdk.PreInitCallback() {

		@Override
		public void onCoreInitFinished() {
			//x5内核初始化完成回调接口,此接口回调并表示已经加载起来了x5,有可能特殊情况下x5内核加载失败,切换到系统内核。
			Log.e("@@","onCoreInitFinished:");
		}

		@Override
		public void onViewInitFinished(boolean b) {
			//x5內核初始化完成的回调,为true表示x5内核加载成功,否则表示x5内核加载失败,会自动切换到系统内核。
			Log.e("@@","加载内核是否成功:" + b);
		}
	});
}

第四步:

文件的下载,支持断点

/**
 * 下载文件
 */
private void downloadFile() {
	new Thread(new Runnable() {
		@Override
		public void run() {
			HttpURLConnection conn = null;
			RandomAccessFile raf = null;
			BufferedInputStream bis = null;
			try {
				//1. 创建文件夹、及文件
				File file = new File(filePah);
				if (!file.getParentFile().exists()) {
					file.getParentFile().mkdirs();
				}
				raf = new RandomAccessFile(file, "rwd");
				URL url = new URL(item.getFileUrl());
				conn = (HttpURLConnection) url.openConnection();
				conn.setConnectTimeout(3000);
				conn.setReadTimeout(3000);
				conn.setRequestMethod("GET");
				getLength();
				finishSize = file.length();
				conn.setRequestProperty("Range", "bytes=" + finishSize + "-");
				raf.seek(finishSize);
				conn.connect();
				bis = new BufferedInputStream(conn.getInputStream());
				int len;
				byte[] buffer = new byte[1024 * 8];
				while (isDownload && (-1 != (len = bis.read(buffer)))) {
					raf.write(buffer, 0, len);
					finishSize += len;
					if (finishSize < fileSize) {
						handler.sendEmptyMessage(0);
					} else {
						//下载完成
						isDownload = false;
						handler.sendEmptyMessage(1);
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
				handler.sendEmptyMessage(-1);
			} finally {
				try {
					if (raf != null) {
						raf.close();
						raf = null;
					}
					if (bis != null) {
						bis.close();
						bis = null;
					}
					if (conn != null) {
						conn.disconnect();
						conn = null;
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}).start();
}

/**
 * 首先开启一个线程去获取要下载文件的大小(长度)
 */
private void getLength() {
	HttpURLConnection connection = null;
	try {
		//连接网络
		URL url = new URL(item.getFileUrl());
		connection = (HttpURLConnection) url.openConnection();
		connection.setConnectTimeout(3000);//连接超时时间
		connection.setReadTimeout(3000);//读取超时时间
		connection.setRequestMethod("GET");//请求类型为GET

		if (connection.getResponseCode() == 200) {//网络连接成功
			fileSize = connection.getContentLength();
		}
	} catch (Exception e) {
		e.printStackTrace();
	} finally {
		try {
			if (connection != null) {
				connection.disconnect();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

第五步:

打开文件

1. 在布局文件中随便创建一个view,用来显示文档

TbsReaderView不支持在布局文件中创建,只能动态添加
mTbsReaderView = new TbsReaderView(this, new TbsReaderView.ReaderCallback() {
	@Override
	public void onCallBackAction(Integer integer, Object o, Object o1) {

	}
});
prview.addView(mTbsReaderView, new LinearLayout.LayoutParams(-1, -1));

2. 缓存目录的创建,如果没有缓存目录,会报空指针异常,TbsReaderTemp

String tbsReaderTemp = Environment.getExternalStorageDirectory() + "/TbsReaderTemp";

打开文件的完整代码:

private void previewDoc() {
	mTbsReaderView = new TbsReaderView(this, new TbsReaderView.ReaderCallback() {
		@Override
		public void onCallBackAction(Integer integer, Object o, Object o1) {

		}
	});
	prview.addView(mTbsReaderView, new LinearLayout.LayoutParams(-1, -1));

	String tbsReaderTemp = Environment.getExternalStorageDirectory() + "/TbsReaderTemp";

	Bundle bundle = new Bundle();
	bundle.putString("filePath", filePah);
	bundle.putString("tempPath", tbsReaderTemp);
	String fileType = item.getFileName().substring(item.getFileName().lastIndexOf(".") + 1);
	boolean result = mTbsReaderView.preOpen(fileType, false);
	if (result) {
		mTbsReaderView.openFile(bundle);
	} else {
		//前面任何一部出错,都可能导致文档打开失败
	}
}

第六步:

关闭文档的时候一定要关闭TbsReaderView,否则再次打开文档失败。

if (mTbsReaderView != null) {
	mTbsReaderView.onStop();
	mTbsReaderView.destroyDrawingCache();
}

ok.腾讯TBS打开文档的介绍到此介绍。

发布了33 篇原创文章 · 获赞 20 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/huangwenkui1990/article/details/90600237