我需要访问用户通常可以访问的所有文件和文件夹,因为在应用程序场景中用户应该选择一个文件夹来下载文件。 我的应用程序通过启动设置活动陷入了无限循环。 我尝试使用
requestIntent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION, Uri.parse("package:" + BuildConfig.APPLICATION_ID));
if(hasPerms == true){
}else {
intentActivityResultLauncher.launch(requestIntent);
}
private ActivityResultLauncher<Intent> intentActivityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult o) {
if (o.getResultCode() == RESULT_OK) {
//...
}else{
//...
}
}
});
根据12 android的设置UI,我已经获得了权限。 但如果我尝试检查授予的权限,我会得到错误的结果。
hasPerms = checkSelfPermission(Manifest.permission.MANAGE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
Log.i(TAG, "onStart: "+hasPerms);
hasPerms = checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
Log.i(TAG, "onStart: "+hasPerms);
hasPerms = checkSelfPermission(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION) == PackageManager.PERMISSION_GRANTED;
Log.i(TAG, "onStart: "+hasPerms);
所有 Log.i 方法都会在 logcat 中打印 false。
我已经在清单中声明了我的权限:
<manifest xmlns:androi="http://schemas.android.com/apk/distribution"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" tools:ignore="ScopedStorage"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
如果我尝试使用
Manifest.MANAGE_EXTERNAL_STORAGE
请求许可,我将收到“活动未找到”异常。
经过一番思考后,我得出了这个解决方案: 我可以使用
SharedPrefernes
而不是 checkSelfPermission
方法检查授予的权限。因此,当结果代码正常时,我只是将值 "true"
放入缓存字符串中。然后在启动活动时简单地检查它。
创建一个意图来请求管理所有文件权限。
Intent requestIntent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
获取 SharedPrefences 实例
SharedPreferences cache = getSharedPreferences("cache", Context.MODE_PRIVATE);
在方法
onActivityResult
中创建一个结果启动器,如果结果正常,则只需使用 SharedPrefernes.Editor
将带有值的字符串放入缓存中
private ActivityResultLauncher<Intent> intentActivityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult o) {
if(o.getResultCode() == RESULT_OK) {
cache.edit().putString("perms","true").commit();
//...
}else {
//...
}
}
});
然后通过检查应用程序缓存中的字符串值来检查权限。
if(cache.getString("perms","false").equals("false")) {
intentActivityResultLauncher.launch(requestIntent);
}