The Android framework supports various cameras and its features to allow you capture images and videos in your applications. In this lesson, we will give you a quick view about how to integrate and control camera in your application.
Implementation of camera in your application can be done through the integration of an existing Android Camera application. You can start the existing Android Camera application via an intent and use the returned data of the application to access the result. Also, you can directly integrate the camera into your application via the Camera API (which uses android.hardware.camera2, added in API Level 21). If you use the Camera API, you need to add the following permissions.
• Intent: We can capture the images and video without using an instance of Camera class, but, you should make use of the constants of MediaStrore class.
ACTION_IMAGE_CAPTURE:For capturing image
ACTION_VIDEO_CAPTURE: For capturing video
• Camera: It is the main class of camera API which can be used to capture image and video.
• SurfaceView: It provides a dedicated drawing surface embedded inside a view hierarchy.
• MediaRecorder: Used to record audio and video.
The following example illustrates how to use an inbuilt camera application in the application using intents.
First create MainActivity.java under src/<your packagename> in your application.
MainActivity.java:
[java]
public class MainActivity extends Activity {
//variable declaration
private static final int CAMERA= 0;
Context context;
ImageView image;
@Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
//hide action bar
requestWindowFeature(Window.FEATURE_NO_TITLE);
//set activity to external view
setContentView(R.layout.activity_main);
context=this;
Button camera=(Button)findViewById(R.id.button1);
image=(ImageView)findViewById(R.id.imageView1);
//on click camera
camera.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, CAMERA);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==CAMERA)
{
Bitmap bp = (Bitmap) data.getExtras().get("data");
image.setImageBitmap(bp);
}
}
}
[/java]
Create activity_main.xml under res/layout folder
activity_main.xml:
[xml]
[/xml]
AndroidManifest.xml:
[xml]
[/xml]
Output: