Jake
Jake

Reputation: 16837

Android intent - pass uri to camera

I am trying to test the sample code related to capturing an image via camera. The documentation says that a URI can be passed as an extra in the intent were the camera will save the image.

I tried the following :

// image1 doesn't exist
File file = new File(getFilesDir() + "/image1");
Uri uri = Uri.fromFile(file);

Intent i = new Intent();
i.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
i.putExtra(MediaStore.EXTRA_OUTPUT, uri);

if (i.resolveActivity(getPackageManager()) != null) {
     startActivityForResult(i, 1337);
}

I am trying to place the image as a file named image1 in my files directory. I am testing this on the genymotion VM. I have tested getting the image as a bitmap in the return Intent, but when I use the above approach, the camera app gets stuck when I click done after taking the picture.

I'm guessing it has something to do with URI permissions. Do I need to add some permissions in the intent like in data sharing ?

Edit:

I tried to follow these instructions, except I want to save the photo in my app's directory, so I tried the following but it doesn't work (the app has camera permission) :

 String imagePath = null;
 try {
      File image = File.createTempFile("testImage", ".jpg", getFilesDir());
      imagePath = "file://" + image.getAbsolutePath();
 }
 catch(Exception e){
    Toast.makeText(getApplicationContext(), "" + e.getMessage(), Toast.LENGTH_SHORT).show();
 }

 File file = new File(imagePath);
 Uri uri = Uri.fromFile(file);


 Intent i = new Intent();
 i.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
 i.putExtra(MediaStore.EXTRA_OUTPUT, uri);

 if (i.resolveActivity(getPackageManager()) != null) {
    startActivityForResult(i, 1337);
 }

I also have onActivityResult(), but its no use, as the camera app gets stuck as explained above.

Also, an additional question : When I don't have camera permission in my test app, I can still invoke the camera and the get the bitmap in intent extra, how so ? Is this something specific to genymotion VM ?

Upvotes: 1

Views: 881

Answers (1)

reidisaki
reidisaki

Reputation: 1524

Make sure you have these permissions for your manifest

 <uses-permission android:name="android.permission.CAMERA" />
 <uses-feature android:name="android.hardware.camera" />
 <uses-feature android:name="android.hardware.camera.autofocus" />

Everything looks good to me. Do you have onActivityResult()

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

    if (requestCode == 1) {
        if(resultCode == RESULT_OK){
            String result=data.getStringExtra("result");
        }
        if (resultCode == RESULT_CANCELED) {
            //Write your code if there's no result
        }
    }
}//onActivityResult

Upvotes: 1

Related Questions