capturing images with MediaStore.ACTION_IMAGE_CAPTURE intent in android

前端 未结 2 1281
甜味超标
甜味超标 2020-11-30 04:11

I am capturing images using MediaStore.ACTION_IMAGE_CAPTURE intent. it is working fine in most of the devices. but it is not working correctly in some latest android device

相关标签:
2条回答
  • 2020-11-30 04:47

    My onActivityResult() method looks like this and it works in obtaining the image from MediaStore.ACTION_IMAGE_CAPTURE:

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            Bundle extras = data.getExtras();
            Bitmap mImageBitmap = (Bitmap) extras.get("data");
        }
    }
    
    0 讨论(0)
  • 2020-11-30 04:57

    Photos taken by the ACTION_IMAGE_CAPTURE are not registered in the MediaStore automatically on all devices.

    The official Android guide gives that example: http://developer.android.com/guide/topics/media/camera.html#intent-receive But that does not work either on all devices.

    The only reliable method I am aware of consists in saving the path to the picture in a local variable. Beware that your app may get killed while in background (while the camera app is running), so you must save the path during onSaveInstanceState.

    Edit after comment:

    Create a temporary file name where the photo will be stored when starting the intent.

    File tempFile = File.createTempFile("my_app", ".jpg");
    fileName = tempFile.getAbsolutePath();
    Uri uri = Uri.fromFile(tempFile);
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
    startActivityForResult(intent, PICTURE_REQUEST_CODE);
    

    fileName is a String, a field of your activity. You must save it that way:

    @Override
    public void onSaveInstanceState(Bundle bundle)
    {
     super.onSaveInstanceState(bundle);
     bundle.putString("fileName", fileName);
    }
    

    and recover it in onCreate():

    public void onCreate(Bundle savedInstanceState)
    {
     if (savedInstanceState != null)
      fileName = savedInstanceState.getString("fileName");
     // ...
    }
    

    Now, at the time of onActivityResult, you know the name of the file where the photo was stored (fileName). You can do anything you wish with it, and then delete it.

    2013-09-19 edit: It seems that some camera apps ignore the putExtra uri, and store the pic in a different place. So, before using the value of fileName you should check whether the intent is null or not. If you get a non-null intent, then you should prefer intent.getData() over fileName. Use fileName as a backup solution only when it is needed.

    0 讨论(0)
提交回复
热议问题