我正在尝试从相机获取图像,并直接保存到我的应用程序的私有文件目录中。出于安全考虑,该图像不应在任何时候公开访问。
一般来说,授予对私有文件的临时访问权限的方法是使用ContentProvider并在Intent中设置GRANT_WRITE_URI_PERMISSION标志。根据FileProvider中的文档,我已经完成了以下步骤:
AndroidManfiest.xml
<manifest>
...
<application>
...
<provider
android:authorities="com.my.domain"
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/file_paths" />
</provider>
...
res/xml/file_paths.xml
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<files-path name="my_images" path="images/"/>
</paths>
当启动相机活动时,我从一个活动中执行以下操作:
File imageFile = getInternalImageFile();
Uri captureUri = FileProvider.getUriForFile(this, "com.my.domain", imageFile);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// grant temporary access to the file
intent.setData(captureUri);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
// tell the camera where to save the file
intent.putExtra(MediaStore.EXTRA_OUTPUT, captureUri);
startActivityForResult(intent, IMAGE_CAPTURE_REQUEST_CODE);
然而,这会导致相机应用程序立即返回而不执行任何操作。我怀疑是因为它没有预料到意图(Intent.setData())上有任何数据。
以上策略效果不佳。那么,我该如何将从相机拍摄的图像安全地直接保存到我的应用程序的私有文件目录中?