在互联网上搜索了有关授予写权限和被弃用函数回溯的信息后,我找到了两个术语,它们可以让我获得更新在下载文件夹中创建的文件的权限:来自存储访问框架的ACTION_OPEN_DOCUMENT_TREE和ActivityCompat.requestPermissions()
然而,虽然存储访问框架没有提供我想要的东西(人们选择了保存点,所以无论他们选择哪一个,我都需要权限才能工作),但我不能让requestPermissions()函数工作。
那么,你如何获得许可来更改应用程序在某个地方创建的文件(通过Storage Acces Frame),可能是以一种在Android 9-11中工作的方式。最好是在Kotlin,但在这一点上我并不挑剔,你能给我的任何东西我都会改编
编辑:忘了提了,我使用的文件是包含Json数据的Textfile文件
请帮帮忙
发布于 2021-06-11 05:23:04
如果你正在使用媒体文件,并针对android Q或更多,这可能会起作用:
假设您已经获得了想要修改的文件uri,您可以将访问文件的代码放在try-catch块中,然后可以从其中获取actionIntent并请求用户授予修改特定文件的权限的RecoverableSecurityException,以下是用于此操作的示例代码
private fun onDeleteClick(uri: Uri?) {
uri?.let {
try {
contentResolver.delete(it,null,null)
} catch (se:SecurityException){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q){
val securityException = se as RecoverableSecurityException
val intentSender = securityException.userAction.actionIntent
startIntentSenderForResult(intentSender.intentSender,0x11,null,0,0,0)
} else
{
throw SecurityException()
}
}
}
}要监听用户对权限请求的响应,您可以像这样覆盖onRequestPermissionsResult
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
if (requestCode == 1){
if (grantResults[0] == PackageManager.PERMISSION_GRANTED ){
//you should be able to modify file now
} else {
Toast.makeText(this,"Permission was denied to access files",Toast.LENGTH_LONG).show()
}
}
}https://stackoverflow.com/questions/67926834
复制相似问题