Home > OS >  How to access any file based on the path name in android 10 devices
How to access any file based on the path name in android 10 devices

Time:11-07

In devices below android 10 we can access any file like this:: File f = new File("storage/emulated/0/filename.txt");

But I want to do to same on android 10 devices which are using something like scoped storage or mediastore class that I didn't understood in android studio I don't know exactly how to do it I want to access files any directories not only public directories like "Pictures" please help me

File f = new File("storage/emulated/0/file.jpg");

CodePudding user response:

You'll need to request MANAGE_EXTERNAL_STORAGE permission. With that permission, you can access shared storage files with the File API.

Reference:

https://developer.android.com/training/data-storage/manage-all-files#all-files-access

CodePudding user response:

To get all the files of folder xyz (storage/emulated/0/xyz) below android 10:

File xyzFolder = new File(Environment.getExternalStorageDirectory()   File.separator   "xyz");

File[] allFiles = xyzFolder.listFiles();

But for android 10 and above either use declare MANAGE_EXTERNAL_STORAGE (not recommended if it's not some kind of file manager app) or you can use below method:

1). First take folder permission

uriMain = Uri.parse("content://com.android.externalstorage.documents/tree/primary:Android/media/document/primary:xyz");

private final int REQUEST_CODE = 100;

List<Object> filesList = new ArrayList<>();

private void aboveQFolderPermission() {

    try {
        Intent createOpenDocumentTreeIntent = null;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            createOpenDocumentTreeIntent = ((StorageManager) getSystemService(STORAGE_SERVICE)).getPrimaryStorageVolume().createOpenDocumentTreeIntent();
        }

        assert createOpenDocumentTreeIntent != null;
        String replace = createOpenDocumentTreeIntent.getParcelableExtra("android.provider.extra.INITIAL_URI").toString().replace("/root/", "/document/");
        createOpenDocumentTreeIntent.putExtra("android.provider.extra.INITIAL_URI", Uri.parse(replace   ":"   "xyz"));
        startActivityForResult(createOpenDocumentTreeIntent, REQUEST_CODE);
    } catch (Exception e) {
        e.printStackTrace()
    }

}

Now in onActivityResult(),

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == REQUEST_CODE) {
        if (data != null) {
            getContentResolver().takePersistableUriPermission(data.getData(), Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);

            //save shared preference to check whether app specific folder permission granted or not
            sharedPreferences = getSharedPreferences("tree", MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPreferences.edit();

            editor.putString("treeUriString", String.valueOf(uriMain));
            editor.apply();

            new Thread(() -> {
                getListAboveQ(uriMain);
                handler. Post(() -> /*Some code here as per your need*/);
            }).start();

        }
    }
}

2). Now get the List of files:

private void getListAboveQ(uriMain) {


    ContentResolver contentResolver = getContext().getContentResolver();
    Uri buildChildDocumentsUriUsingTree = DocumentsContract.buildChildDocumentsUriUsingTree(uriMain, DocumentsContract.getDocumentId(uriMain));

    try (Cursor cursor = contentResolver.query(buildChildDocumentsUriUsingTree, new String[]{"document_id"}, null, null, null)) {
        while (cursor.moveToNext()) {
               filesList.add(DocumentsContract.buildDocumentUriUsingTree(uriMain, cursor.getString(0)));
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

}
  • Related