如何在Android中从通知打开文件夹/目录



fun showNotification(({

val path = Environment.getExternalStorageDirectory().toString() + "/Android/media/"
val uri = Uri.parse(path)
val intent = Intent(Intent.ACTION_PICK)
intent.setDataAndType(uri, "*/*")
val activityPendingIntent = PendingIntent.getActivity(
context,
1,
intent,
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) PendingIntent.FLAG_IMMUTABLE else 0
)
val notification = NotificationCompat.Builder(context, COUNTER_CHANNEL_ID)
.setSmallIcon(R.drawable.ic_download_done)
.setContentTitle("Download Finished")
.setContentText("Files at Android/media/")
.setContentIntent(activityPendingIntent)
.build()
notificationManager.notify(1, notification)

}

这是我的代码,我只能打开文件夹,但无法打开文件。

我想做的只是重定向到文件夹并访问其中的文件。这可能吗?我是不是搞错了?

经过彻底的搜索,我找到了一个适合我的答案

// my notification function
fun showNotification(){

// an intent to be initialized when:
lateinit var intent: Intent
// A) Android version is 10 or above
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
val sm = context.getSystemService(Context.STORAGE_SERVICE) as StorageManager
intent = sm.primaryStorageVolume.createOpenDocumentTreeIntent()
var startDir = "Android%2Fmedia" // here is the directory you wanted to open. feel free to test based on your needs.
var uri: Uri = intent.getParcelableExtra("android.provider.extra.INITIAL_URI")!!
var scheme = uri.toString()
scheme = scheme.replace("/root/", "/document/");
scheme += "%3A$startDir";
uri = Uri.parse(scheme);
intent.putExtra("android.provider.extra.INITIAL_URI", uri);
// B) Android Versions 9 and below
} else {
val path = Environment.getExternalStorageDirectory().toString() + "/Android/media/yourpackagename" // path of the directory you wanted to open
val uri = Uri.parse(path)
intent = Intent(Intent.ACTION_PICK)
intent.putExtra("android.provider.extra.INITIAL_URI", uri)
intent.setDataAndType(uri, "*/*")
}

val activityPendingIntent = PendingIntent.getActivity(
context,
1,
intent,
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) PendingIntent.FLAG_IMMUTABLE else 0
)
// shows notification
val notification = NotificationCompat.Builder(context, COUNTER_CHANNEL_ID)
.setSmallIcon(R.drawable.ic_download_done)
.setContentTitle("Download Finished")
.setContentText("Locate at Files:Android/media/net.pregi.netmesh2/NetMesh")
.setContentIntent(activityPendingIntent)
.build()
notificationManager.notify(1, notification)
}

注意,对于android 9及以下版本,我只打开了文件夹,但无法打开其中的文件。仍在寻找答案。作为参考,以下是我发现的与此事有关的链接。仍然可以接受建议。

Android 11 ACTION_OPEN_DOCUMENT_TREE

如何在android 中使用intent打开存储中的特定文件夹

最新更新