问题描述
下一个删除我应用程序拥有的文件的代码可以正常工作,RecoverableSecurityException
也不例外,因为该文件是由我的应用程序创建的(使用ContentResolver.insert(...)
方法)
getVideoFileContentUri(context,file)?.let { uri ->
try {
context.contentResolver.delete(uri,null,null)
} catch (securityException: RecoverableSecurityException) {
val intentSender =
securityException.userAction.actionIntent.intentSender
intentSender?.let {
activity.startIntentSenderForRecsult(
intentSender,REQUEST_CODE,null
)
}
}
}
fun getVideoFileContentUri(context: Context,file: File): Uri? {
val filePath = file.absolutePath
val cursor = context.contentResolver.query(
MediaStore.Video.Media.EXTERNAL_CONTENT_URI,arrayOf(MediaStore.Video.Media._ID),MediaStore.Video.Media.DATA + "=? ",arrayOf(filePath),null
)
return if (cursor != null && cursor.moveToFirst()) {
val id: Int = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID))
cursor.close()
Uri.withAppendedPath(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,"" + id)
} else {
null
}
}
但是,如果我使用ContentResolver.update(...)
方法更新由应用创建的文件,则删除该文件将需要权限-它会抛出RecoverableSecurityException
并启动意图,这将打开一个系统对话框以确认修改文件
// here I change file name of the file
val contentValues = ContentValues(1).apply {
put(MediaStore.Video.Media.DISPLAY_NAME,"SOME NEW FILE NAME")
}
contentResolver.update(uri,contentValues,null)
所以现在看来我的应用程序不拥有该文件,要删除该文件,我的用户必须确认每个文件的删除
这真的很烦人,我该如何解决这个问题?
对于ContentResolver.update(...)
应用创建的您自己的文件,在ContentResolver.insert(...)
之后失去了修改此文件的权限,将需要请求
解决方法
我找到了解决方法。
创建文件时,我们需要将put(MediaStore.*.Media.IS_PENDING,1)
添加到内容值:
val contentValues = ContentValues(5).apply {
put(MediaStore.Video.Media.IS_PENDING,1)
put(MediaStore.Video.Media.DISPLAY_NAME,"INITIAL FILENAME")
put(MediaStore.Video.Media.DATE_ADDED,System.currentTimeMillis() / 1000)
put(MediaStore.Video.Media.MIME_TYPE,"video/mp4")
put(MediaStore.Video.Media.RELATIVE_PATH,relativePath)
}
val uri = resolver.insert(
MediaStore.Video.Media.EXTERNAL_CONTENT_URI,contentValues
)
然后,当您完成文件处理(例如,使用MediaRecorder
完成该文件的视频录制)后,您可以像这样更新它(您必须添加put(MediaStore.*.Media.IS_PENDING,0)
:
val contentValues = ContentValues(2).apply {
put(MediaStore.Video.Media.IS_PENDING,0)
put(MediaStore.Video.Media.DISPLAY_NAME,"NEW FILENAME,E.G. APPENDING END RECORDING TIMESTAMP TO PREVIOUS FILE NAME")
}
resolver.update(uri,contentValues,null,null)
然后在调用ContentResolver.delete(...)
函数时,不再需要请求许可(不再抛出RecoverableSecurityException
)
try {
resolver.delete(uri,null)
} catch (securityException: RecoverableSecurityException) {
val intentSender =
securityException.userAction.actionIntent.intentSender
intentSender?.let {
activity.startIntentSenderForRecsult(
intentSender,REQUEST_CODE,null
)
}
用户不会感到烦恼:)
尽管如果用户重新安装您的应用,您先前创建的所有文件都需要权限请求,是的,从Android Q开始并不容易...:)