Android Camera Example/Tutorial
In this post, I will show you how to use a camera to record video and click images.This post shows using android system camera as of now Camera API is deprecated for API level 21 or greater. So to work with API level 21 or greater follow new Camera2 API.In This Post, we will work on Camera for API level less than 21.
So, Let’s Start:-
1.Open Android Studio -> New Project->Android Application Project-> Name of Application-> Follow all instructions and complete by clicking on Finish.
2.To use Camera in our Application add following permission to AndroidManifest.xml
<uses-feature android:name="android.hardware.camera" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.RECORD_AUDIO" />
3. Create a layout containing buttons to click an image and to record video.
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"> <Button android:id="@+id/clickimage" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Click Image" android:layout_alignParentBottom="true"/> <Button android:id="@+id/recordvideo" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Capture Video" android:layout_above="@+id/clickimage"/> </RelativeLayout>
4. Now create MainActivity.java and code to click image and record video.
MainActivity.java
package com.coderzpassion.camerasample; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Environment; import android.provider.MediaStore; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.Toast; import java.io.File; import java.text.SimpleDateFormat; import java.util.Date; public class MainActivity extends AppCompatActivity { //code for Activity result private static final int CAPTURE_IMAGE_REQUEST_CODE=1000; private static final int CAPTURE_VIDEO_REQUEST_CODE=1001; private static final int IMAGE=2000; private static final int VIDEO=2001; // button to click image and record video Button clickimage,recordvideo; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); clickimage=(Button)findViewById(R.id.clickimage); recordvideo=(Button)findViewById(R.id.recordvideo); clickimage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(checkIfCameraAvailable()) { clickImage(); } else { Toast.makeText(MainActivity.this,"Camera Not Available",Toast.LENGTH_SHORT).show(); return; } } }); recordvideo.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(checkIfCameraAvailable()) { recordVideo(); }else { Toast.makeText(MainActivity.this,"Camera Not Available",Toast.LENGTH_SHORT).show(); return; } } }); } //method to click image private void clickImage() { Intent intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE); File file=getOutputMediaFile(IMAGE); intent.putExtra(MediaStore.EXTRA_OUTPUT, file); //intent to get Image intent startActivityForResult(intent, CAPTURE_IMAGE_REQUEST_CODE); } //method to record video private void recordVideo() { Intent intent=new Intent(MediaStore.ACTION_VIDEO_CAPTURE); File file=getOutputMediaFile(VIDEO); intent.putExtra(MediaStore.EXTRA_OUTPUT,file); startActivityForResult(intent,CAPTURE_VIDEO_REQUEST_CODE); } //check if camera is available in device public boolean checkIfCameraAvailable() { if(MainActivity.this.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) { //camera is available return true; } else { //camera is not available return false; } } //method to get the path for video and image private static File getOutputMediaFile(int type) { // get path of pictures directory and name a folder in it as MyCameraApp File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "MyCameraApp"); //check if directory not exists and if not then create directory if (!mediaStorageDir.exists()) { if (!mediaStorageDir.mkdirs()) { Log.d("MyCameraApp", "failed to create directory"); return null; } } // get current date and time String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); File mediaFile; //if type is image then create path to store image and name it as currentdateandtime.jpg if(type==IMAGE) { mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg"); } //if type is video then create path to store video and name it as currentdateandtime.mp4 else if(type==VIDEO) { mediaFile = new File(mediaStorageDir.getPath() + File.separator + "VID_" + timeStamp + ".mp4"); } else { return null; } return mediaFile; } //getting activity result @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { //if capturing image if(requestCode==CAPTURE_IMAGE_REQUEST_CODE) { // successfully captured if(resultCode==RESULT_OK) { Toast.makeText(MainActivity.this," Image Captured Successfully",Toast.LENGTH_SHORT).show(); } else { Toast.makeText(MainActivity.this,"Error Capturing Image! Please Retry",Toast.LENGTH_SHORT).show(); } } //if capturing video else if(requestCode==CAPTURE_VIDEO_REQUEST_CODE) { //if captured video successfully if(resultCode==RESULT_OK) { Toast.makeText(MainActivity.this," Video Saved Successfully",Toast.LENGTH_SHORT).show(); } else { Toast.makeText(MainActivity.this,"Error Capturing Video! Please Retry",Toast.LENGTH_SHORT).show(); } } super.onActivityResult(requestCode, resultCode, data); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.coderzpassion.camerasample" > <uses-feature android:name="android.hardware.camera" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.RECORD_AUDIO" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
Output