首先要提的是,问题的答案
here
不要帮忙。
源代码如下所示:
Intent intent = new Intent("com.mycompany.action.PICK_FILE");
String authority = "com.mycompany.fileprovider";
File file = Environment.getExternalStorageDirectory();
intent.setData(FileProvider.getUriForFile(this, authority, file));
FileProvider.getUriForFile
正在引发异常,下面是堆栈跟踪:
java.lang.StringIndexOutOfBoundsException: length=15; index=16
at java.lang.String.indexAndLength(String.java:500)
at java.lang.String.substring(String.java:1313)
at android.support.v4.content.FileProvider$SimplePathStrategy.getUriForFile(FileProvider.java:687)
at android.support.v4.content.FileProvider.getUriForFile(FileProvider.java:377)
在
AndroidManifest.xml
里面
application
我添加了以下标签:
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.mycompany.fileprovider"
android:exported="false"
android:grantUriPermissions="true"
>
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths"
/>
</provider>
内容
file_paths.xml
如下所示:
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="input_files" path="." />
<external-path name="output_files" path="MyAppName/" />
</paths>
output_files
此上下文中未使用路径。
我已经运行了调试器
FileProvider.SimplePathStrategy.getUriForFile()
. 相关代码段如下(第683-688行):
final String rootPath = mostSpecific.getValue().getPath();
if (rootPath.endsWith("/")) {
path = path.substring(rootPath.length());
} else {
path = path.substring(rootPath.length() + 1);
}
rootPath
被评估为
/storage/sdcard
这也是
path
因此,不奇怪会抛出异常。
我做错什么了?
更新:
如以下建议,通过
java.io.File
不应是目录。
Docs
模棱两可的,从不直截了当地说。解决方法是“手动”创建URI。因此
intent.setData(FileProvider.getUriForFile(this, authority, file));
应替换为:
intent.setData(Uri.parse("content://" + file.getAbsolutePath()));