takePersistableUriPermission()(SAF)上的java.lang.SecurityException

时间:2016-06-23 13:57:16

标签: java android android-intent sd-card securityexception

我使用存储访问框架在SD卡上获取写访问权限(API> = 21)。

它在大多数设备上运行良好,但有些像Galaxy S7(Edge,API 23)在调用takePersistableUriPermission()时抛出SecurityException。

appmanifest

代码:

Caused by: java.lang.SecurityException: No persistable permission grants found for UID 10150 and Uri 0 @ content://com.android.externalstorage.documents/tree/70CD-6B92

所有S7设备都不会发生异常。我已经在2台设备上成功测试了代码,但是这个抛出了SecurityException。

我是否必须在SAF的电话中添加一些标志?

//call the SAF
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
                        startActivityForResult(intent, Config.REQUEST_SAF);

//Persist permissions
int flags = resultData.getFlags();
flags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

this.getContentResolver().takePersistableUriPermission(treeUri, flags); //throws exception

感谢任何帮助。

2 个答案:

答案 0 :(得分:0)

尝试添加此flag

intent.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);

答案 1 :(得分:0)

我尝试在grantUriPermission之前添加takePersistableUriPermission,这对我来说是唯一有效的,可以避免系统SecurityException引发的错误:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
try {
    getContext().grantUriPermission(getContext().getPackageName(), uri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
} catch (IllegalArgumentException e) {
    // on Kitkat api only 0x3 is allowed (FLAG_GRANT_READ_URI_PERMISSION | FLAG_GRANT_WRITE_URI_PERMISSION)
    getContext().grantUriPermission(getContext().getPackageName(), uri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
} catch (SecurityException e) {
    Log.e("", e.toString());
}

try {
    int takeFlags = intent.getFlags();
    takeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
    getContext().getContentResolver().takePersistableUriPermission(uri, takeFlags);
} catch (SecurityException e) {
    Log.e("", e.toString());
}
}