Simple Android Directory picker - How?

拜拜、爱过 提交于 2020-05-24 21:13:05

问题


I have just started coding in Android Studio and feeling Awesome..!!

How can I write a code for a 'Directory Picker'. i.e., When a button is clicked, a simple Dialog/Activity screen which can show list of directories.

Also, want to store all the files in that directory in to an Array variable. (Once OK button is clicked).

PS: I have searched here and found some cool 'File choose' but m looking for Directory Chooser..!

Thanks in advance.


回答1:


Try to use Intent.ACTION_OPEN_DOCUMENT_TREE

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
            Intent i = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
            i.addCategory(Intent.CATEGORY_DEFAULT);
            startActivityForResult(Intent.createChooser(i, "Choose directory"), 9999);
        }

And get result Uri from onActivityResult data.getData()

@Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch(requestCode) {
            case 9999:
                Log.i("Test", "Result URI " + data.getData());
                break;
        }

    }



回答2:


Also you can use some libraries.
for example:
https://github.com/passy/Android-DirectoryChooser




回答3:


There's an open source library that does directory chooser and open/save file activities as well. It can be found on GitHub at https://github.com/BoardiesITSolutions/FileDirectoryPicker.

Works on Android API Level 17 and above

Disclaimer: I wrote it




回答4:


As of Android 10 (API 29), direct access to external storage is deprecated in favor of storage access framework https://developer.android.com/guide/topics/providers/document-provider




回答5:


Use below code to select directory

        Intent result = new Intent();
        result.putExtra("chosenDir", path);
        setResult(RESULT_OK, result);

And to get the selected path override onActivityResult :

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if(requestCode == PICK_DIRECTORY && resultCode == RESULT_OK) {
        Bundle extras = data.getExtras();
        String path = (String) extras.get("chosenDir");

    }
}


来源:https://stackoverflow.com/questions/27898676/simple-android-directory-picker-how

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!