Search code examples
androidandroid-intentfile-iofile-manager

Android: How to set initial directory in ACTION_GET_CONTENT


I need my users to choose a backup file (to restore) from their external file, and have two issues.

  1. I gave the backup file I am writing an extension of .sbu and I was not able to figure out how to make the file explorer on ACTION_GET_CONTENT intent, to filter only .sbu files. For now though, I set the intent type to */*

  2. The other more important problem I request help with it to set a default initial directory when my INTENT opens up the default file explorer. The following is my current code, but does not seem to work.

    Intent ioIntent = new Intent(Intent.ACTION_GET_CONTENT);
    ioIntent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/simple_information_manager/backup")), "*/*");
    ioIntent.addCategory(Intent.CATEGORY_OPENABLE);
    ioIntent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
    
    if (ioIntent.resolveActivityInfo(parent.getPackageManager(), 0) != null) {
        doExit = false;
        startActivityForResult(Intent.createChooser(ioIntent, getString(R.string.choose_file)), RESTORE);
    } else {
        Snackbar.make(listView.getRootView(), "Directory chooser not available", Snackbar.LENGTH_LONG).show();
    }
    

Solution

  • I gave the backup file I am writing an extension of .sbu and I was not able to figure out how to make the file explorer on ACTION_GET_CONTENT intent, to filter only .sbu files

    That is not possible.

    set a default initial directory when my INTENT opens up the default file explorer

    There is nothing in the ACTION_GET_CONTENT protocol for this. Largely, that is because ACTION_GET_CONTENT is not tied to files and directories.

    Also, there is no "default file explorer", particularly on Android 4.3 and older. You can argue that the Storage Access Framework UI fills that role, though I tend to think of it more as the Android equivalent of "file-open" and "file-save-as" dialogs from desktop OSes and related platforms.

    You have two major courses of action:

    1. Stop thinking in terms of files, extensions, directories, and move firmly into thinking about content. In that case, you could use ACTION_OPEN_DOCUMENT on Android 4.4+. It offers EXTRA_INITIAL_URI, which is reminiscent of your "default initial directory" request.

    2. Stop thinking in terms of using an Intent, and instead use a file/directory chooser library. Those are not as flexible in terms of where the content comes from, but they more fit your file/directory mindset and may offer features more in line with your expectations.