Home Tutorials Training Consulting Products Books Company Donate Contact us

Get more...

Training Events

Lars Vogel (c) 2009, 2016 vogella GmbH Version 1.4, 30.06.2016

Using the Android Camera via Intent and via the API. This tutorial describes how to use the camera API in Android. The tutorial is based on Eclipse 4.2, Java 1.6 and Android 4.2.

1. Android Camera

Most Android devices have at least one camera. Some devices have a front and a back facing camera.

Using the camera on the Android device can be done via the integration of existing camera application. In this case you would start the existing Camera application via an intent and use the return data of the application to access the result.

Alternatively you can also directly integrate the camera into your application via the Camera API.

The following description contains examples for both use cases.

2. Android Basics

The following description assumes that you have already basic knowledge in Android development.

Please check https://www.vogella.com/tutorials/Android/article.html - Android development tutorial, to learn the basics. Also see https://www.vogella.com/android.html - Android development tutorials, for more information about Android development.

3. Tutorial: Using an Intent to make a photo

Create a new Android project de.vogella.android.imagepick with an activity called ImagePickActivity.

Adjust the layout of the activity to contain an ImageView with the result ID. Also add a button with the onClick property pointing to a onClick method.

Change the ImagePickActivity class to the following.

package de.vogella.android.imagepick;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;

public class ImagePickActivity extends Activity {
    private static final int REQUEST_CODE = 1;
    private Bitmap bitmap;
    private ImageView imageView;

    public void onCreate(Bundle savedInstanceState) {
        imageView = (ImageView) findViewById(R.id.result);

    public void onClick(View View) {
        Intent intent = new Intent();
        startActivityForResult(intent, REQUEST_CODE);

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        InputStream stream = null;
        if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK)
            try {
                // recyle unused bitmaps
                if (bitmap != null) {
                stream = getContentResolver().openInputStream(data.getData());
                bitmap = BitmapFactory.decodeStream(stream);

            } catch (FileNotFoundException e) {
            } finally ch (IOException e) {
                if (stream != null)
                    try {
                    } catch (IOException e) {

4. Tutorial: Using the camera API

In this tutorial you create application which allows you to make a photo via the front camera and to save it on the SD card.

If you use the Android emulator ensure that you configured the camera and that you added an SD card during the creation of the your Android virtual device.

Create a new Android project called de.vogella.camera.api with an activity called MakePhotoActivity.

Add the android.permission.CAMERA permission to access your camera and the android.permission.WRITE_EXTERNAL_STORAGE to be able to write to the SD card to your AndroidManifest.xml file.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="15" />
    <uses-permission android:name="android.permission.CAMERA"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

        android:label="@string/app_name" >
            android:label="@string/app_name" >
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />


Change the main.xml file in the <filename class="directory">res/layout_ folder to the following

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="match_parent" >

        android:text="Make Photo" />


Create the following PhotoHandler class which will be responsible for saving the photo the SD card.

package de.vogella.camera.api;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.content.Context;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;

public class PhotoHandler implements PictureCallback {

    private final Context context;

    public PhotoHandler(Context context) {
        this.context = context;

    public void onPictureTaken(byte[] data, Camera camera) {

        File pictureFileDir = getDir();

        if (!pictureFileDir.exists() && !pictureFileDir.mkdirs()) {

            Log.d(MakePhotoActivity.DEBUG_TAG, "Can't create directory to save image.");
            Toast.makeText(context, "Can't create directory to save image.",


        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyymmddhhmmss");
        String date = dateFormat.format(new Date());
        String photoFile = "Picture_" + date + ".jpg";

        String filename = pictureFileDir.getPath() + File.separator + photoFile;

        File pictureFile = new File(filename);

        try {
            FileOutputStream fos = new FileOutputStream(pictureFile);
            Toast.makeText(context, "New Image saved:" + photoFile,
        } catch (Exception error) {
            Log.d(MakePhotoActivity.DEBUG_TAG, "File" + filename + "not saved: "
                    + error.getMessage());
            Toast.makeText(context, "Image could not be saved.",

    private File getDir() {
        File sdDir = Environment
        return new File(sdDir, "CameraAPIDemo");

Change the MakePhotoActivity ` class to the following. This class assumes that you have a button in your layout with the `onClick property pointing to a onClick() method.

package de.vogella.camera.api;

import android.app.Activity;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Camera.CameraInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import de.vogella.cameara.api.R;

public class MakePhotoActivity extends Activity {
    private final static String DEBUG_TAG = "MakePhotoActivity";
    private Camera camera;
    private int cameraId = 0;

    public void onCreate(Bundle savedInstanceState) {

        // do we have a camera?
        if (!getPackageManager()
                .hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
            Toast.makeText(this, "No camera on this device", Toast.LENGTH_LONG)
        } else {
            cameraId = findFrontFacingCamera();
            if (cameraId < 0) {
                Toast.makeText(this, "No front facing camera found.",
            } else {
                camera = Camera.open(cameraId);

    public void onClick(View view) {
        camera.takePicture(null, null,
                new PhotoHandler(getApplicationContext()));

    private int findFrontFacingCamera() {
        int cameraId = -1;
        // Search for the front facing camera
        int numberOfCameras = Camera.getNumberOfCameras();
        for (int i = 0; i < numberOfCameras; i++) {
            CameraInfo info = new CameraInfo();
            Camera.getCameraInfo(i, info);
            if (info.facing == CameraInfo.CAMERA_FACING_FRONT) {
                Log.d(DEBUG_TAG, "Camera found");
                cameraId = i;
        return cameraId;

    protected void onPause() {
        if (camera != null) {
            camera = null;