Android file chooser with specific file extensions

∥☆過路亽.° 提交于 2019-12-17 19:44:58

问题


I need to show only 'pdf' files in my application when I run default File chooser I'm not able to filter file extensions.

    final Intent getContentIntent = new Intent(Intent.ACTION_GET_CONTENT);
    getContentIntent.setType("application/pdf");
    getContentIntent.addCategory(Intent.CATEGORY_OPENABLE);

    Intent intent = Intent.createChooser(getContentIntent, "Select a file");
    startActivityForResult(intent, REQUEST_PDF_GET);

File chooser shows any kinds of files. I would like to show only pdf files. How can i filter files showed by File chooser.


回答1:


It's an unknown to you what user-installed file browser apps your intent may trigger. I think this is a case where's it's better to hand roll something. My approach was to

a) Find all files with a particular extension on external media with something like (I was looking for the .saf extension, so you'd alter for .pdf accordingly):

    public ArrayList<String> findSAFs(File dir, ArrayList<String> matchingSAFFileNames) {
    String safPattern = ".saf";

    File listFile[] = dir.listFiles();

    if (listFile != null) {
        for (int i = 0; i < listFile.length; i++) {

            if (listFile[i].isDirectory()) {
                findSAFs(listFile[i], matchingSAFFileNames);
            } else {
              if (listFile[i].getName().endsWith(safPattern)){
                  matchingSAFFileNames.add(dir.toString() + File.separator + listFile[i].getName());
                  //System.out.println("Found one! " + dir.toString() + listFile[i].getName());
              }
            }
        }
    }    
    //System.out.println("Outgoing size: " + matchingSAFFileNames.size());  
    return matchingSAFFileNames;
}

b) Get that result into a ListView and let the user touch the file s/he wants. You can make the list as fancy as you want -- show thumbnails, plus filename, etc.

It sounds like it would take a long time, but it didn't and you then know the behavior for every device.



来源:https://stackoverflow.com/questions/27407157/android-file-chooser-with-specific-file-extensions

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