用户在文件资源管理器中单击.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();
}
}
这是AndroidManifest
您的<intent-filter>
是说,无论内容来自何处,您都可以处理text/*
内容。
当我尝试打开文件时,我想获取其绝对路径
然后你需要在你的<intent-filter>
中添加<data android:scheme="file">
,以声明你只使用file
方案。您的应用将不再显示为不使用file
Uri
值的应用(例如您正在使用的"文件管理器"(中的选项。而且,由于 Android 7.0+ 上实际上禁止file
Uri
值,因此随着时间的推移,您的应用将变得不那么有用。到2020年左右,你的应用程序将毫无用处。
或者,您可以摆脱"想要获得其绝对路径"的要求。如果要从file
或content
Uri
中检索文本内容,则可以在ContentResolver
上使用openInputStream()
。