Android - 将照片保存到路径 - RESULT_CANCELLED

时间:2016-12-26 19:40:25

标签: android

由于我在不同的设备上有错误,我决定更换整个打开的相机并保存图片代码。我在Android tutorial中使用了完全相同的代码。

我的代码:

private static File createImageFile(Activity activity) throws IOException {
    // Create an image file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";
    File storageDir = activity.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
    File image = File.createTempFile(
            imageFileName,  /* prefix */
            ".jpg",         /* suffix */
            storageDir      /* directory */
    );

    // Save a file: path for use with ACTION_VIEW intents
    photoPath = image.getAbsolutePath();
    return image;
}

private static void dispatchTakePictureIntent(Activity activity) {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    // Ensure that there's a camera activity to handle the intent
    if (takePictureIntent.resolveActivity(activity.getPackageManager()) != null) {
        // Create the File where the photo should go
        File photoFile = null;
        try {
            photoFile = MainActivity.createImageFile(activity);
        } catch (IOException ex) {
            // Error occurred while creating the File
        }
        // Continue only if the File was successfully created
        if (photoFile != null) {
            imageUri = FileProvider.getUriForFile(activity,
                    "com.APPPACKAGE.fileprovider",
                    photoFile);
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            activity.startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
        }
    }
}

在清单文件中:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="18" />

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

使用它在Android 6 Marshmallow上很有用,在Android 4.4 Kitkat上它没有。在Kitkat上onActivityResult我从相机result = 0收到RESULT_CANCELLED

我已检查相机是否能够将照片保存在file_paths.xml中指定的位置,但事实并非如此。这个文件夹中填充了0个字节的文件。

我该怎么做才能解决它?

2 个答案:

答案 0 :(得分:1)

并非所有相机应用都支持content作为EXTRA_OUTPUT Uri的方案。例如,谷歌自己的相机应用程序直到2016年夏天才支持它。而且,由于我们通过额外的Uri传递,我们无法将自己限制为支持content的相机应用。

您的主要选项是:

  1. targetSdkVersion降低到24以下并坚持使用Uri.fromFile(),而不是使用FileProvider

  2. 使用StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().build());停用FileUriExposedException,然后坚持使用Uri.fromFile(),而不是使用FileProvider

  3. 完全废弃ACTION_IMAGE_CAPTURE的使用,直接切换到相机API或通过某个帮助库(例如mine

  4. 从战术上讲,如果你use setClipData() to force granting of permissions on your Uri,你可能会得到更好的结果。

答案 1 :(得分:0)

感谢@CommonsWare,我添加了这段代码并且有效:

if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.LOLLIPOP) {
                takePictureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            }
            else if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.JELLY_BEAN) {
                ClipData clip=
                        ClipData.newUri(activity.getContentResolver(), "A photo", imageUri);

                takePictureIntent.setClipData(clip);
                takePictureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            }
            else {
                List<ResolveInfo> resInfoList=
                        activity.getPackageManager()
                                .queryIntentActivities(takePictureIntent, PackageManager.MATCH_DEFAULT_ONLY);

                for (ResolveInfo resolveInfo : resInfoList) {
                    String packageName = resolveInfo.activityInfo.packageName;
                    activity.grantUriPermission(packageName, imageUri,
                            Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                }
            }
相关问题