Storage Access Framework - failing to obtain document tree from uri (returned from Drive app)

荒凉一梦 提交于 2019-11-28 02:25:28

This is working with Google Drive cloud space but maybe it's a hack. It is not guaranteed to always work.

This example creates a cloud file in a cloud folder that was created by the user (the SAF picker is opened by the app).

Creating the cloud folder (the user has to select the cloud root first from the picker UI)

 Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
 intent.setType("vnd.android.document/directory");
 intent.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
 intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
 startActivityForResult(intent, CREATE_DIRECTORY_REQUEST_CODE);

onActivityResult

@Override
protected void onActivityResult(int requestCode,int resultCode, Intent data) 
{
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == CREATE_DIRECTORY_REQUEST_CODE) 
    {
      if (resultCode == Activity.RESULT_OK) {
      int takeFlags = data.getFlags()
                   &
      (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
      ContentResolver resolver = this.getContentResolver();
      resolver.takePersistableUriPermission(data.getData(),takeFlags);
      archiveUri(data.getData().toString()); //important to save the toString() result, not getPath()
      archiveAuthority(data.getData().getAuthority());
      } 
      else 
      {
            // The user cancelled the request.
      }
    }
}

using the Uri next time

ContentResolver contentResolver;
contentResolver = this.getContentResolver();
uriPath=retrieveArchivedUri();
Uri tempUri;
Uri uri; 
String authority;
tempUri=Uri.parse(uriPath);
authority=retrieveArchivedAuthority();
uri= DocumentsContract.buildDocumentUri(authority,
            DocumentsContract.getDocumentId(tempUri)); //folder Uri

try 
{
 DocumentsContract.createDocument(contentResolver,uri,"plain/text","fileName");
} 
catch (FileNotFoundException e) 
{
        e.printStackTrace();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!