Reputation: 56
After Android 11, we can't access the Android/data directory directly using File I/O. By using SAF, I can now use DocumentFile to traverse the file I want, but when I want to open the file with another app, I find I can't do it. Even if I pass in the correct Uri parameter, the other app can't access the file because it doesn't have permission, which I can understand. But I found an app called "MT Manager" and I was surprised to find that it can open files in any folder in the data directory and use other third-party apps, which is amazing and I can't understand it at all. Please help, do you know what to do?
fun Context.openFile(uri: Uri) {
try {
val intent = Intent(Intent.ACTION_VIEW)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
intent.setDataAndType(uri, MapTable.getMIMEType(uri.toString()))
this.startActivity(intent)
Intent.createChooser(intent, "choose app")
} catch (e: ActivityNotFoundException) {
Toast.makeText(this, "sorry cannot open it!", Toast.LENGTH_SHORT).show()
}
}
This code is valid for files in the normal directory, but not in the Android/data directory after Android 11.
this is which i find MT Manager
I can think of a not very clever method, which is to copy the files in the sdcard/Android/data directory to the sdcard directory, and then call the above method. This works, but it is not good enough. I don’t know what it is. How to achieve it, his effect looks very good.
val extract = {
ctx.toast("please wait...")
val target = File(ROOT_DIR + fileModel.name)
GlobalThreadPools.getInstance().execute {
fileModel.documentFile?.let { doc ->
val fis = ctx.contentResolver.openInputStream(doc.uri)
fis?.let { `is` ->
val bis = BufferedInputStream(`is`)
val fos = FileOutputStream(target)
try {
val buffer = ByteArray(1024)
var len: Int
while (((bis.read(buffer)).also { len = it }) != -1) {
fos.write(buffer, 0, len)
}
Thread.sleep(100)
postUI {
ctx.openFile(target.path)
}
} catch (e: Exception) {
postUI {
ctx.toast("faild!")
}
} finally {
fos.close()
bis.close()
`is`.close()
}
}
}
}
}
Upvotes: 0
Views: 1932