Android Camera Implementation Guide

One way to add a camera function in an Android app is by using the Camera class provided by the Android system or by using third-party libraries like CameraKit. Here is a simple implementation example.

  1. Add camera permission in the Manifest file.
<uses-permission android:name="android.permission.CAMERA" />
  1. Add a button to the layout file for triggering the photo-taking operation.
<Button
    android:id="@+id/btn_take_photo"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Take Photo" />
  1. Get camera instance and set up photo taking listener in Activity.
public class MainActivity extends AppCompatActivity {

    private static final int REQUEST_IMAGE_CAPTURE = 1;
    private Button btnTakePhoto;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btnTakePhoto = findViewById(R.id.btn_take_photo);
        btnTakePhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dispatchTakePictureIntent();
            }
        });
    }

    private void dispatchTakePictureIntent() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
            Bundle extras = data.getExtras();
            Bitmap imageBitmap = (Bitmap) extras.get("data");
            // Do something with the imageBitmap
        }
    }
}

In this example, we start the system camera application by calling the dispatchTakePictureIntent method and get the taken photo after it is captured. We handle the photo result in the onActivityResult method and display or save the photo locally.

bannerAds