feat(file): 添加文件下载完成后打开文件的功能

- 导入 PendingIntent 相关类
- 在下载完成通知中添加打开文件的意图
- 实现构建打开文件 PendingIntent 的方法
- 使用 FileProvider 安全分享文件 URI
- 根据文件扩展名获取正确的 MIME 类型
- 创建带读取权限的查看意图并设置标记兼容性
这个提交包含在:
XuqmGroup 2026-06-05 16:28:34 +08:00
父节点 e9db4b7493
当前提交 2a9b1c0f36

查看文件

@ -2,6 +2,7 @@ package com.xuqm.sdk.file
import android.app.NotificationChannel import android.app.NotificationChannel
import android.app.NotificationManager import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context import android.content.Context
import android.content.Intent import android.content.Intent
import android.net.Uri import android.net.Uri
@ -218,6 +219,7 @@ object FileSDK {
.setSmallIcon(android.R.drawable.stat_sys_download_done) .setSmallIcon(android.R.drawable.stat_sys_download_done)
.setContentTitle(notificationTitle) .setContentTitle(notificationTitle)
.setContentText("下载完成:$resolvedName") .setContentText("下载完成:$resolvedName")
.setContentIntent(buildOpenFilePendingIntent(context, target))
.setAutoCancel(true) .setAutoCancel(true)
.build(), .build(),
) )
@ -281,6 +283,24 @@ object FileSDK {
}) })
} }
private fun buildOpenFilePendingIntent(context: Context, file: File): PendingIntent? =
runCatching {
val mimeType = MimeTypeMap.getSingleton()
.getMimeTypeFromExtension(file.extension.lowercase())
?: "application/octet-stream"
val uri = FileProvider.getUriForFile(context, "${context.packageName}.fileprovider", file)
val view = Intent(Intent.ACTION_VIEW).apply {
setDataAndType(uri, mimeType)
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_ACTIVITY_NEW_TASK)
}
val chooser = Intent.createChooser(view, null).apply {
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
}
val flags = PendingIntent.FLAG_UPDATE_CURRENT or
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) PendingIntent.FLAG_IMMUTABLE else 0
PendingIntent.getActivity(context, file.absolutePath.hashCode(), chooser, flags)
}.getOrNull()
private fun uniqueFile(dir: File, name: String): File { private fun uniqueFile(dir: File, name: String): File {
val base = name.substringBeforeLast('.', name) val base = name.substringBeforeLast('.', name)
val ext = name.substringAfterLast('.', "").let { if (it.isEmpty()) "" else ".$it" } val ext = name.substringAfterLast('.', "").let { if (it.isEmpty()) "" else ".$it" }