收割机 returns 空 URI

Cropper returns null Uri

我的应用程序可以更改用户头像(稍后将其上传到网络服务)。但是在某些设备上,Cropper ("com.android.camera.action.CROP" Intent) 启动了,但是 returns 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);
}

然后在 activity 获取 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);
}

which returns RESULT_OK with null getData():

@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;
}

正如 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
        }
    }
}

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