在Android中如何打开文件浏览器?

14

我正在一台安装了Android 4.0.3系统的设备上进行开发。如何为我的应用程序打开一个文件浏览器呢?在Android SDK中是否有内置的文件浏览器?还是必须自己编写?

我不想让我的应用程序依赖于用户安装单独的文件浏览器应用。

4个回答

22

要从文件浏览器中获取文件,请使用以下方法:

        Intent fileintent = new Intent(Intent.ACTION_GET_CONTENT);
        fileintent.setType("gagt/sdf");
        try {
            startActivityForResult(fileintent, PICKFILE_RESULT_CODE);
        } catch (ActivityNotFoundException e) {
            Log.e("tag", "No activity can handle picking a file. Showing alternatives.");
        }

我不太确定gagt/sdf的作用是什么......但它似乎在我的应用程序中适用于任何文件。

然后添加这个方法:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Fix no activity available
        if (data == null)
            return;
        switch (requestCode) {
        case PICKFILE_RESULT_CODE:
            if (resultCode == RESULT_OK) {
                String FilePath = data.getData().getPath();
                //FilePath is your file as a string
            }
        }

如果用户没有安装或预先安装他们的OEM没有提供文件管理器应用程序,那么您将不得不实现自己的文件管理器。你最好给他们一个选择。


5
我希望这个可以帮助你选择文件:
public void performFileSearch() {

    // ACTION_OPEN_DOCUMENT is the intent to choose a file via the system's file
    // browser.
    Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);

    // Filter to only show results that can be "opened", such as a
    // file (as opposed to a list of contacts or timezones)
    intent.addCategory(Intent.CATEGORY_OPENABLE);

    // Filter to show only images, using the image MIME data type.
    // If one wanted to search for ogg vorbis files, the type would be "audio/ogg".
    // To search for all documents available via installed storage providers,
    // it would be "*/*".
    intent.setType("image/*");

    startActivityForResult(intent, READ_REQUEST_CODE);
}

这段代码来自以下文档:
https://developer.android.com/guide/topics/providers/document-provider.html
请参考该文档获取更多信息。


2

0

没有一款文件管理应用程序可以在所有设备上安装。

您可能希望您的应用程序也能在 Android 3.x 或更低版本的设备上运行。

不过,您最好的选择是编写自己的文件管理器。这并不需要像听起来那么费力,因为网络上已经有很多相关代码了。


1
也许我需要提高我的搜索技巧,但我很难找到一个易于理解的代码示例... - user1451495
http://madteam.co/news/2011/10/android-diy-making-a-file-manager/ 和 https://dev59.com/LW855IYBdhLWcg3w3IRh 这两个链接可以为创建一个简单的文件浏览器提供入门指导。 - poitroae

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接