【问题标题】:View folder contents in Android using default explorer使用默认资源管理器在 Android 中查看文件夹内容
【发布时间】:2015-11-28 04:08:10
【问题描述】:

我想以编程方式启动默认文件资源管理器以显示文件夹的内容。

我正在使用这段代码,但它崩溃了:

    Uri startDir = Uri.fromFile(new File("/sdcard/DCIM/Camera")); 
    Intent intent = new Intent(); 
    intent.setAction(Intent.ACTION_VIEW); 
    intent.setData(startDir);
    startActivity(intent);

LogCat 显示“未找到处理 Intent 的活动”...

我最好的选择是什么?我希望用户看到文件夹的内容并能够单击文件(例如,单击视频并使用默认播放器启动它,单击 PDF 并打开它等)。

【问题讨论】:

    标签: android android-intent


    【解决方案1】:

    不幸的是,似乎没有标准的方法可以做到这一点,我之前一直在寻找完全相同的东西,但找不到任何解决方案。有 2 种替代方法可能适合您:

    1) 使用通用意图并让用户选择他/她的文件管理器 这既安全又简单,但离我们真正想要的有点远

    Uri startDir = Uri.fromFile(new File(Environment.getExternalStorageDirectory()
            .getAbsolutePath() + "/DCIM/Camera"));
        Intent intent = new Intent();
        intent.setData(startDir);
        intent.setType("*/*");
        intent.setAction(Intent.ACTION_VIEW);
        startActivity(intent);
    

    不要使用intent.setType("file/*");,它不是标准的 MIME 类型。

    2) 使用著名文件管理器提供的特定意图 众所周知的文件管理器有自己的自定义意图过滤器,它们接受允许简单浏览的目录路径。其中一些在这里:OI file manager、ES Explorer

    也许您可以检查用户是否安装了这些特定的文件管理器,然后使用此解决方案,否则回退到一般意图。

    目前只有这两个选项。如果我找到更好的解决方案,我会更新这篇文章。

    【讨论】:

    • 感谢您的想法。你能解释一下这条指令到底做了什么吗:intent.setType("*/*"); - 据我所知,这是你的代码和我的代码之间的唯一区别(除了更安全的目录路径),我以前从未使用过这个意图字段。
    • @BogdanAlexandru 这是为了确保设备上安装的每个可能的文件管理器都将显示在“完成操作...”中,"*/*" 是最通用的 MIME 类型,因此任何文件管理器都会没关系。有些人使用intent.setType("file/*");,但这是一个非标准的 MIME,可能会导致程序崩溃。唯一令人讨厌的是setType("*/*") 也会显示其他程序,例如相机、图库等等。
    • 我可以确认使用setType("file/*") 会使我的平板电脑因android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW typ=file/* } 而崩溃
    • 是否需要任何权限?
    • 此代码还显示从谷歌驱动器中选择照片的选项。但是如果从谷歌驱动器中选择文件,它会在 onActivityResult 中返回空路径。那么在这种情况下如何处理?
    【解决方案2】:

    虽然我无法让 OI 文件管理器转到特定目录,但下面直接打开 OI 文件管理器并转到它所在的最后一个目录。

    Intent importFileIntent = new Intent();
    importFileIntent.setType( "file/*" );
    
    // Does nothing. 
    // Uri startingDir = Uri.fromFile( new File(    
    //      Environment.getExternalStorageDirectory().getAbsolutePath() + "/DCIM/Camera"));
    // importFileIntent.setData( startingDirectory );
    
    importFileIntent.setAction( Intent.ACTION_GET_CONTENT );
    
    // Ensure that there's an activity to handle the intent.
    if (importFileIntent.resolveActivity(getPackageManager()) == null) return;
    
    startActivityForResult(importFileIntent, REQUEST_FILE_IMPORT);
    

    如果有人取得进一步的成功,我很乐意听到。

    【讨论】:

    • 您的代码运行良好。但它也显示了用于选择文件的谷歌驱动器。当我从谷歌驱动器中选择一个文件时,它返回 null 。是否有任何解决方案可以隐藏 google drive 选项或获取 google drive 的文件路径。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多