Android SDK Quick Tip: Launching the Camera

Android SDK Quick Tip: Launching the Camera

Tutorial Details
  • Completion Time: 5-10 minutes
  • Difficulty: Beginner
  • Technology: Eclipse + Android SDK

This quick tip shows you how to launch the built-in Camera application and use the results for displaying the captured image. You will achieve this by creating an Intent within your application’s Activity. You’ll then learn how to get and process the Intent’s results and use the resulting image within your application.

Step 1: Create an Android Application

Begin by creating an Android project. Implement your Android application as normal. Once you have a project set up and the application running, decide under what circumstances you want to launch the Camera and retrieve the resulting captured image. Will this occur when a button control is pressed? What will you do with the resulting image? Presumably, you wish to display an appropriately-sized version of the captured image as part of your Activity’s layout—for example, within an ImageView control. Implement the necessary button control, including any click handling. Design the appropriate layout with its ImageView control to contain the resulting photo. Once you have completed these tasks, you have a place to:

  1. Drop in the code to launch the camera
  2. Retrieve and display the resulting photo

Now you are ready to proceed with this quick tip.

Step 2: Creating the Intent

The Camera application can be launched to take a photo with the following Intent:

android.provider.MediaStore.ACTION_IMAGE_CAPTURE

Begin by creating an Intent of this type, as follows, within your button click handler:

Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);

If you just start the Activity like this, the camera application will launch. However, you might want the resulting captured image as well. Luckily, you can retrieve a View-friendly version of the captured camera image as part of the Intent results data.

Step 3: Asking for Results

Intents are often started using the startActivity() method. However, in this case, your application wants to wait for, and use, the results of the Camera application’s image capture. Therefore, you want to send the Intent using the startActivityForResult() call instead. This way you can inspect the results and use the captured image. Therefore, the code should look something like this:

startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);

This will launch an Activity that provides a result, and then pass that result back to the Activity that launched it. If you’re now wondering where CAMERA_PIC_REQUEST comes from, read on.

Step 4: Handling the Results

When the startActivityForResult() method is called, the Activity is launched. Once that Activity finishes, the calling Activity is presented with a result within its onActivityResult() handler. Therefore, you need to implement the onActivityResult() callback method within your application’s Activity as follows:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == CAMERA_PIC_REQUEST) {
        // do something
    }
}

Yes, there it is again: CAMERA_PIC_REQUEST. This is a value that you need to define within your application as the request code returned by the Camera image capture Intent, like so:

private static final int CAMERA_PIC_REQUEST = 1337;

Beyond that, you can use this value to differentiate between different types of results. In this case, just verify that the requestCode is the one you set.

Step 5: Getting the Image

The image that is returned from this is appropriate for display on a small device screen. It comes in directly to the results as an Android Bitmap object:

Bitmap thumbnail = (Bitmap) data.getExtras().get("data");

What you do with the Bitmap object is up to you. Displaying it on screen is as easy as calling the setImageBitmap() method on an ImageView you have defined in your layout (here we’ve called it photoResultView):

ImageView image = (ImageView) findViewById(R.id.photoResultView);
image.setImageBitmap(thumbnail);
Android SDK Take Photo

A Note on Permissions:
Although your application is leveraging the Camera, it is not required to have the android.permission.CAMERA permission since it is not directly accessing the camera. Instead, it’s just launching the Camera application via Intent.

Step 6: Enforcing Device Requirements

So, you’ve seen that it only takes a couple of minutes to add camera capture features to your application. But, guess what? Not all of your users will have Android devices with built-in cameras. Uh-oh!

Luckily, there is a way to help avoid this problem: the <uses-feature> tag of the Android Manifest file. This tells Android Market (and any other interested parties) that your application makes use of the camera and to filter your application accordingly.

To offer your application only to users with devices with camera support, simply add the following tag to your application’s AndroidManifest.xml file:

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

Caveat: Using the <uses-feature> does not guarantee that your app will not be installed on a device without a camera, even if it’s absolutely required. If you only publish through Android Market, though, users with devices without a camera will not see your app listed.

Conclusion

In this quick tip you have learned how to launch the built-in camera application using an Intent and how to retrieve a version of the captured image for use within your own application. Although the resulting image is not the full sized image, the image is much more appropriate for mobile screens and is the fastest and most efficient way to retrieve and display the captured image from the camera. You can, in fact, retrieve the full sized image (often several megapixels and not ideal for display)—but that, my friends, is for another tutorial. ☺

About the Authors

Mobile developers Lauren Darcey and Shane Conder have coauthored several books on Android development: an in-depth programming book entitled Android Wireless Application Development and Sams TeachYourself Android Application Development in 24 Hours. When not writing, they spend their time developing mobile software at their company and providing consulting services. They can be reached at via email to androidwirelessdev+mt@gmail.com, via their blog at androidbook.blogspot.com, and on Twitter @androidwireless.

Need More Help Writing Android Apps? Check out our Latest Books and Resources!

Buy Android Wireless Application Development, 2nd Edition  Buy Sam's Teach Yourself Android Application Development in 24 Hours  Mamlambo code at Code Canyon

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • yokohama

    nice quick tip, thank you! :)

    is launching the camcorder modus as easy like this tutorial?

    • http://androidbook.blogspot.com/ Shane Conder & Lauren Darcey
      Author

      It is similar, but there are some differences in how you get access to the video.

  • http://designturd.tumblr.com Design Turd

    Nice, great tut. You should have made the tut in parts like:
    - idea of an app
    -UI design and icon
    -Basic coding
    -Coding the UI and finally adding animation effects.

    Great tut other than that.

  • A reader

    [offtopic] Tutsplus does not have a mobile version? Ironic..

    • Mätlä

      yes man, very ironic…

  • Lee

    Nice tutorial, can we get the source code for this tutorial? I'm working to create my own version separate from this but seeing the source code would help me a great deal!

  • http://abhinandkr.wordpress.com Abhinand

    Hi,

    Thanks 4 the guide. Works like a charm. But I want the Uri of the clicked image, since the image is stored in my phone's Media Gallery automatically. How do I get it?

    I used the following inside :

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

    if (resultCode == RESULT_OK) {

    if (requestCode == CAMERA_PIC_REQUEST) {

    Uri clickedPhotoUri = data.getData();

    Toast.makeText(getApplicationContext(), clickedPhotoUri.toString(),

    Toast.LENGTH_SHORT).show();

    }

    }

    }

    But, it is getting a null value and the application exits. How do I get the Uri?

    • Vaibhav

      I do have the same problem…

  • Rakesh

    Hi i am using the above code to open camera to capture image.

    It is able to open camera successfully but then giving Null pointer exception…

    can u tell me what the problem might be

  • Umar

    hello,

    using your code works fine for HTC hero but

    when i run exact code in Galaxy S phone
    Bitmap thumbnail = (Bitmap) data.getExtras().get(“data”);

    gives null pointer exception please shed some light on it…

    regards,
    umar

  • Sarun

    After it launched the camera, if the user press back button, the force close happen. How can you fix that?

    • http://dbtek.info Ismail

      Adding a null check solves this.

      if (data != null) {
      Bitmap thumbnail = (Bitmap) data.getExtras().get(“data”);
      }

  • nisanth

    This tutorial is really great….. Very very simple and explains all that we want to know.
    Thanks

  • Khanna

    Thanx for the nice tutorial, really it is helpful………..

    But after launching camera if i press back key, it is causing application to close forcely..

  • Cam

    Thanks for the great tutorial. Works like a charm!

  • ren

    hey man..
    where I call the on activity method and where which parameters I use to call it???

    I did like this and didn’t work..
    protected void onActivityResulty(int requestCode, int resultCode, Intent data){
    if(requestCode==CAMERA_PIC_REQUEST){
    Bitmap thumbnail = (Bitmap) data.getExtras().get(“data”);
    ImageView image = (ImageView) findViewById(R.id.ivProfilePicture);
    image.setImageBitmap(thumbnail);
    }

    }
    public void takepic(){
    Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
    startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
    onActivityResult(1337, 0, cameraIntent);
    }

    but nothing happens.
    what did i miss?
    thanks

    • doosra

      it wont be called like that: onActivityResult(1337, 0, cameraIntent);

      the correct way is mention above: this activity result will be automatically called:

      protected void onActivityResult(int requestCode, int resultCode, Intent data) {
      if (requestCode == CAMERA_PIC_REQUEST) {
      // do something
      }
      }

  • http://emumair.wordpress.com Umair

    A very simple but effective tutorial. Thanks for sharing :)

  • Nesim

    Hi,
    Thanks for great article! But the image quality is so low. How can we make better quality?

    Thanks.

  • Matt

    I’m sorry if this sounds stupid but do you have any tutorials that show how to make the button click handler. I’m very new to this so I’m pretty lost when it says to put this or that inside the button click handler.

    Thanks.

  • Tyler Thomas

    Keeps saying “Cannot connect to camera” error on my Nexus S. Anyone have any ideas? My manifest XML is correctly set with permissions (I believe).

  • Buzby

    “You can, in fact, retrieve the full sized image (often several megapixels and not ideal for display)—but that, my friends, is for another tutorial”

    Please, please, please can you tell me how to retrieve the full sized image – I don’t want to display on-screen but my app would love to be able to save it somewhere so it can ultimately download it to a PC.
    I’m a bit of a newbie on Android so be gentle with me.

  • ivan

    mate great writeup, helped me immensely.. you’r a lej.

  • niluka

    Nice tutorial. Thanks.

  • tomas

    After it launched the camera, if the user press back button, the force close happen. How can you fix that?

  • http://ryan.sadwick.com Ryan Sadwick

    tomas, the back button crashes the app because there aren’t any lifecycle (onSaveInstanceState, onResume, etc) methods in this “quick tip”.

    Please refer to http://developer.android.com/reference/android/app/Activity.html. Understanding lifecycles is very important when developing Android applications.

  • naresh

    Hi, great tutorial for the beginners thank u

  • Amol

    Thanks a lot for this tutorial.

    It worked well on Sony Ericsson (android 2.3.2) but does not call method onActivityResult() when running same code on Samsung Galaxy S2 (android 2.3.3). Any suggestion/information on this please.

  • http://www.epixsystems.co.uk Mike

    Fantastic example. Thank you

  • Lana

    Hi,

    Great thanks for your post. I used your code exactly as is and I was able to take the picture, set it to replace my current ImageView. However, I lost the newly taken picture in my application when I rotate the device (not even pressing any button). Could you please help me out?
    Thanks

  • Gabe

    Is there a source code project for this example or just nothing but code snippets.

  • Vaibhav

    Thanks….for this
    can anyone help me here in camera application..
    I want to take camera image through my application.
    when user capture an image through camera the image should be stored in its default location by name given programatically in the application..
    Thanks in advance…

  • Shahzad

    You have not described about Uri(how can we get it).

  • Shahzad
  • mike

    can u send me all code please???

  • soft_developer

    Hi i am using the above code to open camera to capture image.
    It is able to open camera successfully but onActivityResult the value of the intent is null and the application turns directly to RESULT_CANCELED.

    How can I fix this issue please?

    Thanks

  • terrell

    Thanks, nice tutorial…. worked like a charm…

  • Navdeep

    I can’t explan how much usefull this tutorial for me thanks you very much
    thanks a loat

  • shrawan

    when i am using this code and when press the button its show forcely shut down error