android browse file intent with defined extension

会有一股神秘感。 提交于 2019-11-30 23:10:35

问题


I need to create intent that will open file manager (if any installed) and I want file manager to show only txt files to user, so user couldn't choose file with wrong extension.

    private static final int FILE_SELECT_CODE = 0;

private void showFileChooser() {
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT); 
    intent.setType("*/*");
    intent.addCategory(Intent.CATEGORY_OPENABLE);


    try {
        startActivityForResult(
                Intent.createChooser(intent, "Select txt file"),
                FILE_SELECT_CODE);
    } catch (android.content.ActivityNotFoundException ex) {
        // Potentially direct the user to the Market with a Dialog
        Toast.makeText(this.getActivity(), "Please install a File Manager.", 
                Toast.LENGTH_SHORT).show();
    }
}

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
    case FILE_SELECT_CODE:      
    if (resultCode == Activity.RESULT_OK) {  
        // Get the Uri of the selected file 
        Uri uri = data.getData();
        String path = uri.getPath();
        input = new File(path);
        try {
            txtParser = new TxtFileParser(input);
        } catch (FileNotFoundException e) {
            /* Exception handler must be here! */
        }
    }           
    break;
}
    super.onActivityResult(requestCode, resultCode, data);
}

I managed to do this. But I don't know how to define txt extensions.


回答1:


I want file manager to show only txt files to user, so user couldn't choose file with wrong extension

That is not literally possible. You are welcome to use a MIME type of text/plain instead of */*, but:

  • There is no guarantee that this will only return files with a .txt extension
  • There is no guarantee that there is any app on the device that can handle ACTION_GET_CONTENT of that MIME type
  • There is no guarantee that any "file manager" will honor your MIME type; they may elect to display all files anyway



回答2:


do research on MaterialFilePicker().

new MaterialFilePicker().withFilter(Pattern.compile(".*\.txt$")).start();

like above you can do it using Pattern matching.



来源:https://stackoverflow.com/questions/14626433/android-browse-file-intent-with-defined-extension

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