在使用getPersistedUriPermissions()时,假设它已经包含一些UriPermissions,您如何知道它们是否是您正在尝试执行的操作的正确权限?
例如,如果您获得了对SD卡(或SD卡的一个区域)的写入权限,而用户将SD卡交换为另一个SD卡,则这些权限将不再有效。如何检查函数返回的列表中的权限是否可用(需要重新请求权限)?
以前我只是检查我是否至少有一个权限,但当他们使用多个SD卡等时,这不再起作用。然而,我看不到一种方法来判断列表中的UriPermission是否是我需要的那个。下面是一个例子:
UriPermission {uri=content://com.android.externalstorage.documents/tree/abcdef, modeFlags=3, persistedTime=abcdef}发布于 2016-02-02 10:10:43
这还没有经过严格的测试。我仍然在研究文档API的错综复杂之处(阅读:大量的设计漏洞)。
/**
* Returns the permissible root uri if one exists, null if not.
*
* @return The tree URI.
*/
public Uri getPermissibleRoot(Uri uri)
{
if (uri == null)
return null;
for (UriPermission permission : mRootPermissions)
{
// TODO: This will not work with file schemes, there might not be a way to do so...
String permissionTreeId = DocumentsContract.getTreeDocumentId(permission.getUri());
String uriTreeId = DocumentsContract.getTreeDocumentId(uri);
if (uriTreeId.startsWith(permissionTreeId))
{
return permission.getUri();
}
}
return null;
}这是我正在开发的Android库的一部分。它还远没有准备好进入黄金时间,但我希望让它更容易使用Document API:
发布于 2016-06-01 09:18:49
您应该使用getPersistedUriPermissions()检查权限,如下所示:
private boolean checkStoragePermissions(){
List<UriPermission> list = getContentResolver().getPersistedUriPermissions();
for (int i = 0; i < list.size(); i++){
if(list.get(i).getUri() == myUri && list.get(i).isWritePermission()){
return true;
}
}
return false;
}例如,其中myUri可以是当前安装的SD卡上的uri。
请注意,getUri()返回Uri,但附加了content://com.android.externalstorage.documents/tree/,并且还将符合RFC2396。
示例:我在SD卡上选择了一个名为‘content://com.android.externalstorage.documents/tree/3142-4535%3Axyz’的文件夹,因此getUri()将返回如下内容:xyz
发布于 2021-12-30 01:05:48
这是我对checkStoragePermission的重写
//how to call.
//1. save a granted perm as a string so you can pass it back in
// example: String alreadyHavePermsString="content://com.android.externalstorage.documents/tree/3337-6133%3ASEE";
//
//2.create a Uri by parsing and decoding
// example: Uri treeUri = Uri.parse(Uri.decode(alreadyHavePermsString));
//
//3. return a bool so you know if the permission has been granted
// example boolean bcp = checkStoragePermissions(treeUri);
//
// now the function
private boolean checkStoragePermissions(Uri myUri) //myUri already decoded. see "how to call" #1
{
String sMyUri = myUri.toString(); //%3A already decoded into a ':'
List<UriPermission> list = getContentResolver().getPersistedUriPermissions(); //get the list
for (int i = 0; i < list.size(); i++)
{
UriPermission p = list.get(i); //dereference to isolate the permission and make readable
String strP = Uri.decode(p.getUri().toString()); //decode and stringify for the equals test
if(strP.equals (sMyUri))
{
Log.d("checkstorage","found "+sMyUri); //show status
if(p.isWritePermission()) //now i can reuse the dereferenced permission p
{
return true;
}
}
}
return false;
}https://stackoverflow.com/questions/34340438
复制相似问题