我的Android应用正在磁盘位置上使用Storage Access Framework。
这些位置的典型Uri具有以下形式:
content://com.android.externalstorage.documents/tree/primary:mainFolder/subFolder
如果路径类似于/ mainFolder / subFolder。
该应用程序使用户可以选择(并授权)磁盘上的文件夹。
这是选择器的调用方式:
static public void openPickerForFolderSelection(Activity activity, int requestCode)
{
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
intent.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
activity.startActivityForResult(intent, requestCode);
}
在onActivityResult方法中,以下代码被调用:
static public String takePermanentReadWritePermissions(Activity activity, Intent data)
{
int takeFlags = data.getFlags()
&
(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
ContentResolver resolver = activity.getContentResolver();
resolver.takePersistableUriPermission(data.getData(),takeFlags);
return data.getData().toString(); //very important for archiving the Uri
}
Uri已正确存储为字符串形式(toString())。
这是验证权限的方式(碰巧是我这种情况):
static boolean arePermissionsGranted(Activity activity, String uriString)
{
ContentResolver resolver = activity.getContentResolver();
List<UriPermission> list = resolver.getPersistedUriPermissions();
for (int i = 0; i < list.size(); i++){
if(((Uri.decode(list.get(i).getUri().toString())).equals( uriString)) && list.get(i).isWritePermission()&& list.get(i).isReadPermission()){
return true;
}
}
return false;
}
在应用的另一个位置,必须创建一个文件夹:
/ mainFolder / subFolder / theFolder
以下是创建文件夹的方式:
static public boolean creatFolderInFolder(Activity activity,String parentFolderUriString,String folderName)
{
boolean result=false;
ContentResolver contentResolver;
contentResolver = activity.getContentResolver();
Uri parentFolderUri=null;
parentFolderUri= DocumentsContract.buildDocumentUri(PROVIDER_AUTHORITY,
DocumentsContract.getDocumentId(Uri.parse(parentFolderUriString)));
try {
DocumentsContract.createDocument(contentResolver,parentFolderUri,DocumentsContract.Document.MIME_TYPE_DIR,folderName);
result=true;
} catch (FileNotFoundException e)
{
result =false;
}
return result;
}
使用以下参数执行方法调用:
parentFolderUriString“ content://com.android.externalstorage.documents/tree/primary:mainFolder / subFolder”
folderName“ theFolder”
我得到:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mydomain.app/com.mydomain.app.activityName}: java.lang.IllegalArgumentException: Invalid URI: content://com.android.externalstorage.documents/tree/primary:mainFolder/subFolder
在线:
DocumentsContract.buildDocumentUri(PROVIDER_AUTHORITY,
DocumentsContract.getDocumentId(Uri.parse(parentFolderUriString)));
为什么会出现此错误?