Getting captured image in onActivityResult method

2019-08-11 04:27发布

问题:

i have small doubt in the below code

@Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            Intent i=new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);

            startActivityForResult(i, 0);
        }

    });
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
    super.onActivityResult(requestCode, resultCode, data);

    if(requestCode==0 && resultCode==RESULT_OK ){

        Bundle extras = data.getExtras();
        //get the cropped bitmap
        Bitmap thePic = extras.getParcelable("data");


        ImageView image =(ImageView) findViewById(R.id.imageView1);
        image.setImageBitmap(thePic);

    }
}

In the extras.getParcelable("data"); line of the code here "data" is passed as a key to the parcelable object.

My Question is, is there a key already with the name 'data' defined in the class? or any reason of how this is accepted.

回答1:

It's the camera app's responsibility to add a thumbnail to the Intent you receive in onActivityResult(...). It basically adds a Bitmap value to the intent with "data" as key. Hence it's okay to try and get that value by key from the returned intent. This is also demonstrated in the Taking Photos Simply tutorial on the Android developers website:

Bundle extras = intent.getExtras();
mImageBitmap = (Bitmap) extras.get("data");

However, from experience I can tell not all camera apps honour this behaviour. I wouldn't rely on the data key to actually be there, or the returned intent nog being null for that matter.