我已经更新了我的项目以实现提供者。整个实现似乎是正确的,但是我在StringIndexOutOfBoundsException类内收到了FileProvider异常。

在我的情况下,将创建一个Intent,在该Intent中,用户将在从其图库中获取图像或拍摄新照片之间进行选择。

在这里创建我的一个Intent,然后将其包含在列表中以创建选择器。

    File file = getTempFile(context);
    if (file != null) {
        Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE,
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        takePhotoIntent.putExtra("return-data", true);
        takePhotoIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                FileProvider.getUriForFile(context,                        // line 43
                        BuildConfig.APPLICATION_ID.concat(".fileprovider"),
                        file));
        intentList = addIntentsToList(context, intentList, takePhotoIntent);
    }


getTempFile方法:

private static File getTempFile(Context context) {
    File imageFile = new File(context.getExternalCacheDir(), TEMP_IMAGE_NAME);
    if (imageFile.getParentFile().mkdirs()) {
        return imageFile;
    } else {
        return null;
    }
}


引发的异常:

java.lang.StringIndexOutOfBoundsException: length=86; index=87
     at java.lang.String.substring(String.java:1939)
     at android.support.v4.content.FileProvider$SimplePathStrategy.getUriForFile(FileProvider.java:728)
     at android.support.v4.content.FileProvider.getUriForFile(FileProvider.java:404)
     at com.project.helper.ImagePicker.getPickImageIntent(ImagePicker.java:43)


在这种情况下我该如何进行?可能是此版本的Provider中的错误?接下来,有关我的项目的更多信息:

清单文件:

    <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="com.project.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文件:

<?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-path name="images" path="Android/data/com.project/cache/tempImage" />
</paths>


buildToolsVersion '27.0.2'

最佳答案

更换:

<external-path name="images" path="Android/data/com.project/cache/tempImage" />


与:

<external-cache-path name="images" path="." />


首先,这将更加可靠,因为您当前的实现会假设getExternalCacheDir()指向何处。其次,path需要指向目录,而不是文件,我的猜测是这是横向的。

10-05 20:31
查看更多