Android for Beginners
About Lesson

The camera is one of the most commonly used features of a smartphone. Whether it’s for taking photos, recording videos, or using augmented reality, the camera is a powerful tool that can enhance your apps. In this blog post, we’ll explore how to use the camera in Android.

Step 1: Adding Camera Permission

Before you can access the camera, you need to request the camera permission. This is done by adding the following line to your AndroidManifest.xml file:

<uses-permission android:name="android.permission.CAMERA" />

 

Starting from Android 6.0 (API level 23), you also need to request the camera permission at runtime:

if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, MY_CAMERA_REQUEST_CODE);
}

 

Step 2: Starting the Camera Intent

Android provides a built-in Intent for capturing photos or videos. It’s called MediaStore.ACTION_IMAGE_CAPTURE. Here’s how to start this Intent:

Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, MY_CAMERA_REQUEST_CODE);

This code will start the camera app to capture a photo. If you want to capture a video, you can use MediaStore.ACTION_VIDEO_CAPTURE instead.

 

Step 3: Handling the Camera Result

Once the user has taken a photo or recorded a video, your app will receive the result in the onActivityResult method. Here’s how to handle the result:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == MY_CAMERA_REQUEST_CODE && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
// TODO: Use the photo
}
}

 

In this code, we’re checking if the result comes from the camera Intent and if the result is OK. If so, we’re retrieving the photo from the Intent data.