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

前端 未结 1 1430
孤街浪徒
孤街浪徒 2020-12-07 06:36

My Android app wants to create a folder in Google Drive and get the uri from the Drive app on the device.

It sends an intent, you can see the code below:

<         


        
相关标签:
1条回答
  • 2020-12-07 07:03

    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();
    }
    
    0 讨论(0)
提交回复
热议问题