如何通过其他活动的意图获得结果

时间:2014-09-17 00:08:51

标签: android android-intent android-activity

我正在使用this cropper库。我想从下面的代码块知道,如何在字符串中获得裁剪图像路径的结果?

        Intent intent = new Intent(this, CropImage.class);
        intent.putExtra(CropImage.IMAGE_PATH, imageFilePath);
        intent.putExtra(CropImage.SCALE, true);

        intent.putExtra("outputX", 200); //Set this to define the max size of the output bitmap
        intent.putExtra("outputY", 150); //Set this to define the max size of the output bitmap
        intent.putExtra(CropImage.ASPECT_X, 0);
        intent.putExtra(CropImage.ASPECT_Y, 0);
        startActivity(intent);

2 个答案:

答案 0 :(得分:0)

首先,您需要使用startActivity更改startActivityForResult

如果您已完成此操作,请在您的活动中覆盖onActivityResult,然后执行

String path = data.getStringExtra(CropImage.IMAGE_PATH);

其中data是来自onActivityResult(int requestCode, int resultCode, Intent data)

的Intent对象

答案 1 :(得分:0)

根据the libraries github page上的文档,您应该使用startActivityForResult代替startActivity

通过调用startActivityForResultActivity完成后,onActivityResult将被调用,然后您可以将结果拉出来。

以下代码来自此库的README.md:

开始活动:

private void runCropImage() {
    // create explicit intent
    Intent intent = new Intent(this, CropImage.class);

    // tell CropImage activity to look for image to crop 
    String filePath = ...;
    intent.putExtra(CropImage.IMAGE_PATH, filePath);

    // allow CropImage activity to rescale image
    intent.putExtra(CropImage.SCALE, true);

    // if the aspect ratio is fixed to ratio 3/2
    intent.putExtra(CropImage.ASPECT_X, 3);
    intent.putExtra(CropImage.ASPECT_Y, 2);

    // start activity CropImage with certain request code and listen
    // for result
    startActivityForResult(intent, REQUEST_CODE_CROP_IMAGE);
}

等待结果:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (resultCode != RESULT_OK) {

        return;
    }  

    switch (requestCode) {

        case REQUEST_CODE_CROP_IMAGE:

            String path = data.getStringExtra(CropImage.IMAGE_PATH);

            // if nothing received
            if (path == null) {

                return;
            }

            // cropped bitmap
            Bitmap bitmap = BitmapFactory.decodeFile(mFileTemp.getPath());

            break;
    }
    super.onActivityResult(requestCode, resultCode, data);
}