检索外部存储路径android时发生java.lang.IllegalArgumentException

问题描述 投票:1回答:1

我已经实现了一个Android应用程序,它使用设备相机拍摄图像。我想将图像保存到设备的外部存储目录中。我一直按照android文档中给出here的说明来实现这一点。

这是我的代码:

我在清单文件中添加了提供程序。

<provider
        android:authorities="com.efftronics.android.eEmployee.provider"
        android:name="android.support.v4.content.FileProvider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/provider_paths"/>
    </provider>

xml文件夹中,我创建了paths.xml文件并定义了路径元素。

<?xml version="1.0" encoding="utf-8"?>
    <paths xmlns:android="http://schemas.android.com/apk/res/android">
        <files-path name="my_images" path="images/"/>
        <files-path name="my_docs" path="docs/"/>
    </paths>

这是Java代码:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                //mContext.checkImageDirectories();
                String fileName = EmpConstants.startImgName +
                        new SimpleDateFormat(EmpConstants.PhotoFileFormat, Locale.US).format(new Date());
                File outFile = new File(
                        mContext.getEmpImageDirPath() + fileName + ".jpg");
               // File newfile = new File(outFile,"default_image.jpg");
               /* mCurrentPhotoPath = outFile.getPath();
                cameraOpeningIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(outFile));*/
                Intent i = new Intent(Intent.ACTION_VIEW,FileProvider.getUriForFile(mContext, BuildConfig.APPLICATION_ID +".provider",outFile));
                i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                /*cameraOpeningIntent.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);*/

                startActivityForResult(i, REQUEST_IMAGE_CAPTURE);
            }


        public String getEmpImageDirPath() {
          try {
            return Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).toString()
                    + EmpConstants.appDir;
              } catch (Exception e) {
              Log.d("eEmp/ImgDir", e.toString());
              return "";
        }
}

现在,当我打开相机时,抛出以下异常:

由于java.lang.IllegalArgumentException引发的错误:无法找到包含/storage/emulated/0/DCIM/eEmployee/IMG_20180103_150825.jpg的已配置根目录

我无法弄清楚这个例外的原因。请帮我解决这个问题。

android android-studio file-permissions android-permissions
1个回答
0
投票

你不需要在paths.xml文件中的<files-path name="my_images" path="images/"/>中使用<paths>元素。您关注的链接指出:

<files-path name="name" path="path" />表示应用程序内部存储区域的files/子目录中的文件。该子目录与Context.getFilesDir()返回的值相同。

同样,它也指出:

<external-path name="name" path="path" />Rreresents外部存储区域根目录中的文件。该子目录的根路径与Environment.getExternalStorageDirectory()返回的值相同。

从您上面共享的代码中,我们可以看到您在函数Environment.getExternalStoragePublicDirectory()中使用getEmpImageDirPath()

因此,要解决该错误,您必须替换<files-path name="my_images" path="images/"/>by <external-path name="my_images" path="images/" />

© www.soinside.com 2019 - 2024. All rights reserved.