Storage Access Framework, takePersistableUriPermission

前端 未结 1 1292
清歌不尽
清歌不尽 2021-01-03 14:07

In my application user is able to select the downloads directory. If he selects external removable SD card (not an emulated sd card!, but a memory, which is

相关标签:
1条回答
  • 2021-01-03 14:31

    Thanks to @earthw0rmjim answer, and googling, I figgured out a complete solution:

    public void saveFile() {
        List<UriPermission> permissions = getContentResolver().getPersistedUriPermissions();
        if (permissions != null && permissions.size() > 0) {
            DocumentFile pickedDir = DocumentFile.fromTreeUri(this, permissions.get(0).getUri());
            DocumentFile file = pickedDir.createFile("text/plain", "try2.txt");
            writeFileContent(file.getUri());
        } else {
            Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            intent.setType("text/plain");
    
            startActivityForResult(intent, SAVE_REQUEST_CODE);
        }
    }
    

    So firstly, if we don't have PersistedUriPermissions, it will request such permissions. This way here is how onActivityResult looks like

    public void onActivityResult(int requestCode, int resultCode,
                                 Intent resultData) {
        Uri currentUri = null;
    
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == SELECT_DIR_REQUEST_CODE) {
                if (resultData != null) {
                    Uri treeUri=resultData.getData();
                    Log.d(TAG, "SELECT_DIR_REQUEST_CODE resultData = " + resultData);
                    getContentResolver().takePersistableUriPermission(treeUri, Intent.FLAG_GRANT_READ_URI_PERMISSION
                            | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                    DocumentFile pickedDir = DocumentFile.fromTreeUri(this, treeUri);
                    DocumentFile file = pickedDir.createFile("text/plain", "try2.txt");
                    writeFileContent(file.getUri());
                }
            }
        }
    }
    

    And the writeFileContent looks same as in the question

    private void writeFileContent(Uri uri) {
        try {
            ParcelFileDescriptor pfd =
                    this.getContentResolver().
                            openFileDescriptor(uri, "w");
    
            FileOutputStream fileOutputStream =
                    new FileOutputStream(pfd.getFileDescriptor());
    
            String textContent = "some text";
    
            fileOutputStream.write(textContent.getBytes());
    
            fileOutputStream.close();
            pfd.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    0 讨论(0)
提交回复
热议问题