【问题标题】:How to get file URI when opening file with intent.action.VIEW?使用intent.action.VIEW打开文件时如何获取文件URI?
【发布时间】:2017-06-15 12:15:13
【问题描述】:

用户在文件资源管理器中单击 .txt 文件并获得对话框“打开方式...”,其中列出了我的应用程序。 当我尝试打开文件时,我想获取它的绝对路径。我得到的只是 content:// URI

I/ActivityManager: START u0 {act=android.intent.action.VIEW dat=content://com.android.providers.downloads.documents/document/1031 typ=text/plain

如果我想检索文件的路径,我需要获取 file:// URI。我怎样才能只得到 file:// URI 而不是 content://

这里是 AndroidManifest

        <intent-filter >
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />    
            <data android:mimeType="text/*"/>
        </intent-filter>

这是我尝试处理文件的方式:

Intent i = getIntent();
String action = i.getAction();
String type = i.getType();

if (Intent.ACTION_VIEW.equals(action) && type != null) {
    Uri uri = i.getData();
    if (uri != null) {
        Toast.makeText(this, uri.toString(), Toast.LENGTH_SHORT).show();
    }                 
}

【问题讨论】:

    标签: java android file android-intent uri


    【解决方案1】:

    这里是 AndroidManifest

    您的&lt;intent-filter&gt; 表示您可以处理text/* 的内容无论它来自哪里

    当我尝试打开文件时,我想获取它的绝对路径

    然后您需要将&lt;data android:scheme="file"&gt; 添加到您的&lt;intent-filter&gt;,以声明您仅使用file 方案。在不使用 file Uri 值的应用中,您的应用将不再作为选项出现,例如您正在使用的“文件管理器”。而且,由于 file Uri 值在 Android 7.0+ 上被有效禁止,随着时间的推移,您的应用程序将变得不那么有用。到 2020 年左右,您的应用将毫无用处。

    或者,您可以摆脱“想要获得其绝对路径”的要求。如果您想从filecontent Uri 检索文本内容,您可以在ContentResolver 上使用openInputStream(),例如。

    【讨论】:

    • 但我不仅要读取文件,还要编辑文件并保存。
    • @PersonalJesus:有openOutputStream(),也在ContentResolver。 IOW,与使用绝对路径和FileInputStream/FileOutputStream 相同的事情是使用content UriopenInputStream()/openOutputStream() 可以做的事情。
    • @CommonsWare LibVLC Player Library for Android 不支持 Content Uri,它需要绝对路径,因为它是一个原生库 (c++, c),它对这些东西一无所知!跨度>
    • @user25: 然后只处理文件。使用a file chooser library 而不是给你一个content Uri 的东西。
    • @CommonsWare 文件选择器?我们正在谈论ACTION_VIEW。我有一个应用程序 - 视频播放器。我想从其他应用程序中打开此应用程序中的视频文件 - 资源管理器应用程序,例如play.google.com/store/apps/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-18
    相关资源
    最近更新 更多