Thursday, August 8, 2013

Android Camera Intent Example

Need to incorporate camera into your application? You can follow this instruction HERE provided by Google on creating custom camera app. Or you can do it the easier way which is to start a camera intent. If all you need to do is to capture photos, and do not have the time and resources to create your own custom camera app, then using intent to start the device's camera app is the right way to go. Doing this provides users the ability adjust camera settings provided by the camera app without having you to go through all the trouble creating one from scratch. There are two ways to start a camera intent, which will be described below. In the meantime, if you are eager to look at the source code, it can be view in my android-api-example Github project.

Start Camera Intent without Specified File Path

Basically, all you need to do is create an Intent indicating that you want to capture and image. The value indicating that you would like to capture an image is MediaStore.ACTION_IMAGE_CAPTURE. After when you have created the Intent, we then would want to Activity.startActivityForResult() The reason for using Activity.startActivityForResult() instead of Activity.startActivity() is because we need to retrieve the image that the camera intent returns. You must then override Activity.startActivityForResult() method like in the code below: Since, we have not specified to the camera intent where to save the captured image file, it will return the image as a Bundle within the Intent data. Just as a side note, depending on the device that is being used it will either save a copy of the image file on the device (usually where the camera app saves captured images) or it doesn't.

Start Camera Intent with Specified File Path

In order to provide the Intent with a file path, we must come-up with a file path that we would like it to save it to and the filename. Different device have different starting file paths and to do this safely, I first check there is internal storage available and if there is then I retrieve the root public folder of the device's internal storage. This can be done using Android's Environment class. Then in that public root directory I create a standard Android pictures folder using Environment.DIRECTORY_PICTURES. This code is shown below: Once you have the file path, you just need specify the path into the Intent like this: Then finally in your overridden Activity.startActivityForResult(), since you already know the location of the image, you just need to decode the Bitmap using that file path.


You can view my Android Camera Intent example HERE.
Relevant files are:
src/com/choiboi/apiexamples/camera/CameraMainActivity.java
res/layout/activity_camera_main.xml

Hope this was helpful!!