Andorid 9.0 without Mounted, DocumentFile reads and writes U disk

Under android9.0, FileProvider is only for privacy transfer, and cannot directly create, copy, and move files.

The operation is generally under the primary sd card, if you need to operate the U disk, you need to authorize

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /><uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /><uses-permission android:name="android.permission.MANAGE_DOCUMENTS" />
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MANAGE_MEDIA" />

//Read and write permissions
private static String[] PERMISSIONS_STORAGE = {
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.WRITE_EXTERNAL_STORAGE};
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, PERMISSIONS_STORAGE, REQUEST_PERMISSION_CODE);
    }
}

The second step is to obtain the U disk path: U disk read and write permissions, and then perform path authorization operations. This path is authorized for this path, so it is best to apply for the root path:

Intent intent1 = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
    StorageManager sm = getSystemService(StorageManager.class);

// The path here, the UUID is obtained by querying the database, or through the StorageManager, see the third step for details
    StorageVolume volume = sm.getStorageVolume(new File("/storage/" + UUID));

    if (volume != null) {
        intent1 = volume.createAccessIntent(null)
    }
}

if (intent == null) {
    intent1 = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
}
intent1.setAction(Intent.ACTION_OPEN_DOCUMENT_TREE);
intent1.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
startActivityForResult(intent1, OPEN_DOCUMENT_TREE_CODE);

Attachment: Obtain the UUID path of the U disk to obtain the code, compile the framework by yourself or use reflection:

(1) Method 1
String authority = "com.android.externalstorage.documents";
        final Uri rootsUri = DocumentsContract.buildRootsUri("com.android.externalstorage.documents");
        ContentResolver resolver = getContentResolver();
        final ContentProviderClient client = resolver.acquireUnstableContentProviderClient(
                authority);
        final PackageManager pm = getPackageManager();
        ProviderInfo provider = pm.resolveContentProvider(
                authority, PackageManager.GET_META_DATA);
        if (provider == null) {
            Log.w(TAG, "Failed to get provider info for " + authority);
        }
        if (!provider.exported) {
            Log.w(TAG, "Provider is not exported. Failed to load roots for " + authority);
        }
        if (!provider.grantUriPermissions) {
            Log.w(TAG, "Provider doesn't grantUriPermissions. Failed to load roots for "
                    + authority);
        }

        if (!android.Manifest.permission.MANAGE_DOCUMENTS.equals(provider.readPermission)
                || !android.Manifest.permission.MANAGE_DOCUMENTS.equals(provider.writePermission)) {
            Log.w(TAG, "Provider is not protected by MANAGE_DOCUMENTS. Failed to load roots for "
                    + authority);
        }

        Cursor cursor = null;
        try {
            cursor = client.query(rootsUri, null, null, null, null);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        while (cursor.moveToNext()) {
            String rootId = getCursorString(cursor, DocumentsContract.Root.COLUMN_ROOT_ID);
            String title = getCursorString(cursor, DocumentsContract.Root.COLUMN_TITLE);
            String summary = getCursorString(cursor, DocumentsContract.Root.COLUMN_SUMMARY);
            String documentId = getCursorString(cursor, DocumentsContract.Root.COLUMN_DOCUMENT_ID);
            long availableBytes = getCursorLong(cursor, DocumentsContract.Root.COLUMN_AVAILABLE_BYTES);
            long capacityBytes = getCursorLong(cursor, DocumentsContract.Root.COLUMN_CAPACITY_BYTES);
            String mimeTypes = getCursorString(cursor, DocumentsContract.Root.COLUMN_MIME_TYPES);
//            if("primary".equals(rootId)){

                Log.e(TAG, "rootId:" + rootId + "title:" + title
                        +"summary:" + summary +"documentId:" + documentId +"availableBytes:" + availableBytes +"capacityBytes:" + capacityBytes +"mimeTypes:" + mimeTypes);
//            }
        }

(2) Method 2

final StorageManager sm = getSystemService(StorageManager.class);
final List<StorageVolume> volumes = sm.getStorageVolumes();
HashMap<String, String> paths = new HashMap<>();
volumes.forEach(new Consumer<StorageVolume>() {
    @Override
    public void accept(StorageVolume volume) {
        String state = volume.getState();
if (!volume.isPrimary()){
    File path = volume.getPathFile();
    Log.v("storageVolume:", "path" + path.exists());
    Log.v("storageVolume:", "path isDirectory" + path.isDirectory());
    Log.v("storageVolume:", "path isFile " + path.isFile());
    Log.v("storageVolume:", "path " + path.getAbsolutePath());
    Log.v("storageVolume:", "UUID: " + volume.getUuid())

}
}

at last. We can add, delete, modify and check files. Up to now, the U disk path acquisition and authorization have been OK. Next, we will operate the U disk, add, delete, modify and check

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
        case OPEN_DOCUMENT_TREE_CODE:
            if (data != null && data.getData() != null) {
                Uri uri = data.getData();
                Log.i(TAG,"DocumentsUtils.OPEN_DOCUMENT_TREE_CODE : "  + uri);
                getUsbDrivePath(uri);
            }
            break;
    }
    super.onActivityResult(requestCode, resultCode, data);
}
private void getUsbDrivePath(Uri uri) {
    DocumentFile uRootFile = DocumentFile.fromTreeUri(MainActivity.this,uri);

    uRootFile.listFiles(); //All files
    uRootFile.findFile("file name");//Find the file
    uRootFile.findFile("file name").delete();//delete file
    Uri fileUrl = uRootFile.findFile("").getUri();
    InputStream inputStream = getContentResolver().openInputStream(fileUrl);//read and write files
    createFile creates a file
    createDirectory creates a folder
    delete() delete

}

InputStream inputStream = mContext.getContentResolver().openInputStream(documentFIle.getUri());

OutputStream outputStream = mContext.getContentResolver().openOutputStream(documentFIle.getUri());

read and write.

おすすめ

転載: blog.csdn.net/Angle_Byron/article/details/129561969