文章目錄
- 前言
- 一、效果圖
- 二、實現步驟
- 1.去官網注冊并創建應用[騰訊官網](https://console.cloud.tencent.com/tbs/client)
- 2.下載arr文件并引入[騰訊TBS](https://download.csdn.net/download/Android_Cll/91764395)
- 3.application實例化
- 4.activity實例化
- 5.下載網絡文件
- 6.PreviewActivity預覽
- 7.preview布局
- 總結
前言
做Android的各位,是不是覺得移動端去搞這個文件預覽很操蛋,而且還是各種文件預覽,如果只是PDF可以直接搞定,要預覽各種文件怎么辦,不接第三方怎么弄,猝死都弄不了的,相信我,來吧,今天就是為這個問題來的。
一、效果圖
還是老樣子,先來張效果圖穩定軍心。
二、實現步驟
1.去官網注冊并創建應用騰訊官網
2.下載arr文件并引入騰訊TBS
代碼如下(示例):
//騰訊TBS文件預覽
implementation fileTree(dir: 'libs', include: ['TbsFileSdk_base_arm64_1.0.5.6000094.20250604183426.aar'])
3.application實例化
代碼如下(示例):
//騰訊TBS初始化fun initEngineAsync() {//設置 licenseKeyTbsFileInterfaceImpl.setLicenseKey("你自己的licensekey")val callback: ITbsReaderCallback = object : ITbsReaderCallback {override fun onCallBackAction(actionType: Int, args: Any, result: Any) {println("初始化actionType=$actionType,args=$args,result=$result")// ITbsReader.OPEN_FILEREADER_ASYNC_LOAD_READER_ENTRY_CALLBACK 的值為7002,不是錯誤碼if (ITbsReader.OPEN_FILEREADER_ASYNC_LOAD_READER_ENTRY_CALLBACK === actionType) {val ret = args as Int // 錯誤碼為 actionType == 7002時 args 的值if (ret == 0) {// 初始化成功println("初始化成功了-----")} else {// 初始化失敗println("初始化失敗了-----")}}}}if (!TbsFileInterfaceImpl.isEngineLoaded()) {TbsFileInterfaceImpl.initEngineAsync(this, callback)}}
4.activity實例化
代碼如下(實例化成功才能有后續哦):
//定義變量
private var isInit = false
//實例化
var ret = initEngine(this)if (ret == 0) {println("初始化成功--->界面")isInit = true} else {println("初始化失敗--->界面")}
5.下載網絡文件
//docurl下載文件地址,filename本地存儲路徑,endname文件格式fun download(docUrl: String, fileName: String, endName: String) {DialogUtils.showLoadingDialog(this)val filePath =getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).toString() + "/" + fileName // 本地存儲路徑// 下載文件(可以使用 OkHttp、Retrofit 或原生 HttpURLConnection)Thread {try {val url = URL(docUrl)val connection: HttpURLConnection = url.openConnection() as HttpURLConnectionconnection.setRequestMethod("GET")connection.setDoInput(true)connection.connect()val file = File(filePath)if (!file.exists()) {file.createNewFile()}connection.getInputStream().use { `in` ->FileOutputStream(file).use { out ->val buffer = ByteArray(1024)var len: Intwhile ((`in`.read(buffer).also { len = it }) != -1) {out.write(buffer, 0, len)}out.flush()}}// 下載完成后,在主線程打開文件runOnUiThread {openExternalFilesDirDocument(filePath, endName)DialogUtils.hideLoadingDialog()}} catch (e: Exception) {e.printStackTrace()runOnUiThread {ToastUtils.showToast("下載失敗")}}}.start()}//打開預覽private fun openExternalFilesDirDocument(filePath: String, extName: String) {if (isInit) {if (TbsFileInterfaceImpl.canOpenFileExt(extName)) {startActivity(Intent(this, PreviewActivity::class.java).putExtra("filePath",filePath).putExtra("fileExt", extName).putExtra("url", zhlist[0]))finish()} else {ToastUtils.showToast("此類型文檔暫不支持打開")// tbs 不支持打開的類型}} else {Toast.makeText(applicationContext,"Engine未初始化成功,無法打開文件",Toast.LENGTH_SHORT).show()}}
6.PreviewActivity預覽
class PreviewActivity : BaseActivity() {private lateinit var mFlRoot: FrameLayoutprivate lateinit var mRl: RelativeLayoutprivate var isDestroyed = falseprivate lateinit var imag_fh: ImageViewprivate lateinit var relaitve_xyb: RelativeLayoutoverride fun getContentViewId(): Int {return R.layout.preview}override fun initView(savedInstanceState: Bundle?) {mFlRoot = findViewById(R.id.content)mRl = findViewById(R.id.reader_top)imag_fh = findViewById(R.id.imag_fh)relaitve_xyb = findViewById(R.id.relaitve_xyb)imag_fh.setOnClickListener(this)relaitve_xyb.setOnClickListener(this)val filePath = intent.getStringExtra("filePath").toString()val fileExt = intent.getStringExtra("fileExt").toString()openFile(filePath, fileExt)}override fun onClick(v: View?) {when (v?.id) {R.id.imag_fh -> finish()//下載R.id.relaitve_xyb -> {downloadFile(this, intent.getStringExtra("url").toString(), "下載文檔")}}}fun downloadFile(context: Context, url: String?, fileName: String?) {val downloadManager = context.getSystemService(DOWNLOAD_SERVICE) as DownloadManagerval uri = Uri.parse(url)val request = DownloadManager.Request(uri)// 設置通知欄提示(下載中、完成)request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)// 設置保存路徑(Android 10+ 需使用 MediaStore API 或保存到 Downloads 目錄)request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName)// 發起下載downloadManager.enqueue(request)ToastUtils.showToast("已開始下載,請注意導航欄下載進度")}fun openFile(filePath: String, fileExt: String) {//設置回調val callback =ITbsReaderCallback { actionType, args, result ->println("actionType=$actionType,args=$args,result=$result")if (ITbsReader.OPEN_FILEREADER_STATUS_UI_CALLBACK == actionType) {if (args is Bundle) {val id = (args as Bundle).getInt("typeId")if (ITbsReader.TBS_READER_TYPE_STATUS_UI_SHUTDOWN == id) {finish() // 加密文檔彈框取消需關閉 activity}}}}//設置參數val param = Bundle()param.putString("filePath", filePath)param.putString("fileExt", fileExt) // 文件后綴名,如文件名為 test.pdf,則只需要傳入"pdf"param.putString("tempPath", getExternalFilesDir("temp")!!.absolutePath)//調用openFileReader打開文件mFlRoot.post {val height = mFlRoot.height// 自定義 layout 模式必須設置這個值,否則可能導致文檔內容顯示不全param.putInt("set_content_view_height", height)val ret = TbsFileInterfaceImpl.getInstance().openFileReader(this@PreviewActivity, param, callback, mFlRoot)}}// 銷毀資源使用 onpause + ondestroy 的方式。避免 onDestroy 延遲回調private fun destroy() {if (isDestroyed) {return}// 回收資源mFlRoot.removeAllViews() //移除內容顯示區域 layoutTbsFileInterfaceImpl.getInstance().closeFileReader() //關閉 fileReaderisDestroyed = true}override fun onPause() {super.onPause()if (isFinishing) {destroy()}}public override fun onDestroy() {super.onDestroy()destroy()}//橫豎屏切換override fun onConfigurationChanged(@NonNull newConfig: Configuration) {super.onConfigurationChanged(newConfig)mFlRoot.viewTreeObserver.addOnGlobalLayoutListener(object : OnGlobalLayoutListener {override fun onGlobalLayout() {mFlRoot.viewTreeObserver.removeOnGlobalLayoutListener(this)val w = mFlRoot.widthval h = mFlRoot.heightTbsFileInterfaceImpl.getInstance().onSizeChanged(w, h)}})}
}
7.preview布局
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:background="@color/backColor"android:orientation="vertical"><FrameLayoutandroid:id="@+id/content"android:layout_width="match_parent"android:layout_below="@+id/reader_top"android:layout_height="match_parent"/><RelativeLayoutandroid:id="@+id/relaitve_xyb"android:layout_width="240dp"android:layout_height="48dp"android:layout_alignParentBottom="true"android:layout_centerHorizontal="true"android:layout_marginBottom="10dp"><ImageViewandroid:layout_width="match_parent"android:layout_height="match_parent"android:scaleType="fitXY"android:src="@mipmap/scmbback" /><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_centerInParent="true"android:text="下載"android:textColor="#ffffff"android:textSize="16dp" /></RelativeLayout>
</RelativeLayout>
總結
到此結束就解決了Android文件預覽問題,如果有疑問隨時評論區見。