Cropper返回null Uri

时间:2015-03-06 09:38:28

标签: android android-intent camera gallery

我的应用有可能更改用户头像(后者将其上传到网络服务)。但是在某些设备上,Cropper(" com.android.camera.action.CROP" Intent)启动,但返回null Uri。你能指出我做错了吗?

第一位用户选择照片:

public static void pickPhoto(final Context context) {
    Intent pickImageIntent = new Intent(Intent.ACTION_GET_CONTENT);
    pickImageIntent.setType("image/*");
    ((ActionBarActivity) context).startActivityForResult(Intent.createChooser(pickImageIntent, "Select Avatar"), SettingsActivity.REQUEST_CODE_PICK_AVATAR);
}

然后在活动获得RESULT_OK(选择图像uri)后 - 它开始裁剪:

public static void startCropper(final Context context, final Uri imageToCrop) {
    final Intent intent = new Intent("com.android.camera.action.CROP");
    intent.setData(imageToCrop);
    intent.putExtra("outputX", 200);
    intent.putExtra("outputY", 200);
    intent.putExtra("aspectX", 1);
    intent.putExtra("aspectY", 1);
    intent.putExtra("scale", true);
    intent.putExtra("noFaceDetection", true);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(getTempFile(context)));
    intent.putExtra("return-data", true);
    ((ActionBarActivity) context).startActivityForResult(intent, SettingsActivity.REQUEST_CODE_CROP_AVATAR);
}

返回带有null getData()的RESULT_OK:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_CODE_CROP_AVATAR && resultCode == RESULT_OK) {
        Uri uri = data.getData(); // uri is null on some devices
    }
}

我的getTempFile方法:

public static File getTempFile(Context context) {
    File cacheDir;
    if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        cacheDir = context.getCacheDir();
    } else {
        cacheDir = context.getExternalCacheDir();
    }
    File file = new File(cacheDir, "temp_avatar.jpg");
    try {
        file.createNewFile();
    } catch (IOException e) {
    }
    return file;
}

1 个答案:

答案 0 :(得分:2)

正如greenapps在问题评论中所提到的,如果uri为null,则需要在 onActivityResult()中进行额外检查,然后再使用getExtra(“data”),如下所示:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_CODE_CROP_AVATAR && resultCode == RESULT_OK) {
        Uri uri = data.getData();
        if (null != uri) {
            // do something with uri
        } else {
            Bitmap bitmap = data.getExtra("data");
            // get uri from bitmap and do something with uri
        }
    }
}

在我的应用中测试代码并且工作正常。