【问题标题】:Open folder on card打开卡上的文件夹
【发布时间】:2014-07-21 08:04:00
【问题描述】:

我认为这是非常简单的事情,但它比整个应用程序的其余部分给了我更多的工作。

我只想要一个按钮来打开我的应用程序的“已下载文件”文件夹。就这样。没有文件选择器,没什么复杂的。按钮所要做的就是打开一个包含默认应用程序的文件夹(如果没有默认应用程序,则打开应用程序选择器)。

我尝试了我在 StackOverflow 上看到的不同解决方案,但似乎没有什么对我有用。

示例 1:

Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
Uri uri = Uri.parse(Environment.getExternalStorageDirectory().getPath() + "/MyDownloadedFiles/");
intent.setDataAndType(uri, "text/plain");
startActivity(Intent.createChooser(intent, getString(R.string.action_downloaded)));

在我的 Android 4.4 上,这会打开 KitKat 文件选择器,甚至没有在我想要的文件夹中打开......它似乎默认为卡根。但我确定该文件夹存在并且提供给 Intent 的路径确实是正确的。

示例 2:

Intent intent = new Intent(Intent.ACTION_VIEW);
Uri uri = Uri.parse(Environment.getExternalStorageDirectory().getPath() + "/MyDownloadedFiles/");
intent.setDataAndType(uri, "text/plain");
startActivity(Intent.createChooser(intent, getString(R.string.action_downloaded)));

这会打开一些空白活动,并弹出一个提示:“获取文件内容时发生错误:MyDownloadedFiles”。

我怎样才能让我的应用只拥有一个快捷方式,指向将内容放入的文件夹?

【问题讨论】:

    标签: android android-intent android-sdcard


    【解决方案1】:

    哇.. 终于!!在我尝试了很多事情之后,唯一可行的方法是首先将 URI 字符串包装到一个文件中,然后执行一个 Uri.fromFile:

    File file = new File(Environment.getExternalStorageDirectory().getPath() + "/MyDownloadedFiles/");
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setDataAndType(Uri.fromFile(file), "*/*");
    startActivity(Intent.createChooser(intent, getString(R.string.action_downloaded)));
    

    【讨论】:

    • 那么,转换(听起来很奇怪)和"*/*" 的组合是关键吗?不是"*/*alone?或者,仅仅是转换?
    • 我认为这里的关键是 File 对象可能会在前面加上“file://”或其他任何东西,这使得它可以工作。 "/" 不一定是解决方案,因为如果我在类型中使用 "Uri.parse()" 和 "/",它将不起作用 -将与我上面的示例 1 一样。
    • 你一直“不写”星号(*)对我来说很奇怪......无论如何,如果 kitkat 要求这样做,你可以稍微简化代码如果你保持请记住,Environment.getExternalStorageDirectory() 已经为您提供了一个 File 对象(最好保持简单,这样我们就不会创建从 File 到 String 到 File 到 Uri 的神话:P)。恭喜!
    • 哦,星号没有出现,因为它们变成了粗体。很抱歉。
    • 没问题。无论如何,这个问题是一个很好的提醒,让我们对每个 Android 版本都保持警惕:)
    【解决方案2】:

    我认为这个对你有用:

    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    Uri uri = Uri.parse(Environment.getExternalStorageDirectory().getPath()
        + "/yourFolder/");
    intent.setDataAndType(uri, "*/*");
    startActivity(Intent.createChooser(intent, "Open /sdcard/yourFolder"));
    

    【讨论】:

    • 你好。我已经尝试过了,它与我的示例 1 非常相似。唯一的区别是类型。在使用 text/plain 之前,我尝试使用 /
    猜你喜欢
    • 2011-08-22
    • 2022-07-24
    • 1970-01-01
    • 2020-01-14
    • 2014-04-11
    • 2012-09-20
    • 1970-01-01
    • 2012-09-21
    • 2013-02-01
    相关资源
    最近更新 更多