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打開文檔的介紹到此介紹。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章