SlideShare a Scribd company logo
1 of 3
Camera
The Android framework includes support for various
cameras and camera features available on devices,
allowing you to capture pictures and videos in your
applications.
The BASICS
The Android framework supports capturing images
and video through
the android.hardware.camera2 API or
camera Intent. Here are the relevant classes:
android.hardware.camera2
This package is the primary API for controlling
device cameras. It can be used to take pictures or
videos when you are building a camera application.
Camera
This class is the older deprecated API for
controlling device cameras.
SurfaceView
This class is used to present a live camera preview
to the user
MediaRecorder
This class is used to record video from the camera.
Intent
An intent action type
of MediaStore.ACTION_IMAGE_CAPTURE or Med
iaStore.ACTION_VIDEO_CAPTURE can be used
to capture images or videos without directly using
the Camera object.
Creating a new project
Open your Android Studio and create a new blank
activity application.
The first step is to add the android permissions and
required features.
Add these lines to your AndroidManifest.xml:
<uses-permission
android:name="android.permission.CAMERA" />
<uses-feature
android:name="android.hardware.camera" />
Inside your style.xml, just edit the line to remove
the ActionBar, if you prefer(this is removed just to
have a full-screen camera):
<style name="AppTheme"
parent="Theme.AppCompat.Light.NoActionBar">
Create this basic activity_main.xml:
<FrameLayout
xmlns:android="http://schemas.android.com/apk/re
s/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<FrameLayout
android:id="@+id/camera_view"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imgClose"
android:layout_gravity="right|top"
android:background="@android:drawable/ic_menu
_close_clear_cancel"
android:padding="20dp"/>
</FrameLayout>
Here we have a simple FrameLayout.
The camera_view will display the camera data,
that we’ll use later with OpenGL and some
algorithms to process it.
And the ImageButton will be used to close the
application.
III - Camera code
The first step is to create a SurfaceView. It’ll
receive camera data and display it inside the
FrameLayout.
Create a new file, CameraView.java in the same
folder that your MainActivity.java is.
First, just extend the SurfaceView and implements
the SurfaceHolder.Callback.
You’ll have something like this code:
public class CameraView extends SurfaceView
implements SurfaceHolder.Callback{
public CameraView(Context context, Camera
camera){
super(context);
}
@Override
public void surfaceCreated(SurfaceHolder
surfaceHolder) {
}
@Override
public void surfaceChanged(SurfaceHolder
surfaceHolder, int i, int i2, int i3) {
}
@Override
public void surfaceDestroyed(SurfaceHolder
surfaceHolder) {
}
}
Add these two private variables:
private SurfaceHolder mHolder;
private Camera mCamera;
And then just update your CameraView constructor
with:
public CameraView(Context context, Camera
camera){
super(context);
mCamera = camera;
mCamera.setDisplayOrientation(90);
//get the holder and set this class as the callback,
so we can get camera data here
mHolder = getHolder();
mHolder.addCallback(this);
mHolder.setType(SurfaceHolder.SURFACE_TYPE
_NORMAL);
}
Now, override these methods, I commented
everything to help you:
@Override
public void surfaceCreated(SurfaceHolder
surfaceHolder) {
try{
//when the surface is created, we can set the
camera to draw images in this surfaceholder
mCamera.setPreviewDisplay(surfaceHolder);
mCamera.startPreview();
} catch (IOException e) {
Log.d("ERROR", "Camera error on
surfaceCreated " + e.getMessage());
}
}
@Override
public void surfaceChanged(SurfaceHolder
surfaceHolder, int i, int i2, int i3) {
//before changing the application orientation, you
need to stop the preview, rotate and then start it
again
if(mHolder.getSurface() == null)//check if the
surface is ready to receive camera data
return;
try{
mCamera.stopPreview();
} catch (Exception e){
//this will happen when you are trying the camera
if it's not running
}
//now, recreate the camera preview
try{
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
} catch (IOException e) {
Log.d("ERROR", "Camera error on
surfaceChanged " + e.getMessage());
}
}
@Override
public void surfaceDestroyed(SurfaceHolder
surfaceHolder) {
//our app has only one screen, so we'll destroy the
camera in the surface
//if you are unsing with more screens, please
move this code your activity
mCamera.stopPreview();
mCamera.release();
}
III - Camera Activity
Now, inside you MainActivity.java, add these
variables:
private Camera mCamera = null;
private CameraView mCameraView = null;
No, override the method bellow, I commented to
help you to understand it:
protected void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try{
mCamera = Camera.open();//you can use
open(int) to use different cameras
} catch (Exception e){
Log.d("ERROR", "Failed to get camera: " +
e.getMessage());
}
if(mCamera != null) {
mCameraView = new CameraView(this,
mCamera);//create a SurfaceView to show camera
data
FrameLayout camera_view =
(FrameLayout)findViewById(R.id.camera_view);
camera_view.addView(mCameraView);//add the
SurfaceView to the layout
}
//btn to close the application
ImageButton imgClose =
(ImageButton)findViewById(R.id.imgClose);
imgClose.setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View view) {
System.exit(0);
}
});
}
Now, you can run your app.

More Related Content

Viewers also liked

Viewers also liked (9)

Bouwaanvraag hoger amstellaan
Bouwaanvraag hoger amstellaanBouwaanvraag hoger amstellaan
Bouwaanvraag hoger amstellaan
 
Sistema de direcci+¦n
Sistema de direcci+¦nSistema de direcci+¦n
Sistema de direcci+¦n
 
Gaceta mayo junio 2013
Gaceta mayo junio 2013Gaceta mayo junio 2013
Gaceta mayo junio 2013
 
Presentación1
Presentación1Presentación1
Presentación1
 
Adobe dreamweaver
Adobe dreamweaverAdobe dreamweaver
Adobe dreamweaver
 
Qué es un servidor
Qué es un servidorQué es un servidor
Qué es un servidor
 
Presentación1
Presentación1Presentación1
Presentación1
 
Ferramentas da web 2.0
Ferramentas da web 2.0Ferramentas da web 2.0
Ferramentas da web 2.0
 
Universidad nacional de chimborazo
Universidad nacional de chimborazoUniversidad nacional de chimborazo
Universidad nacional de chimborazo
 

Similar to Camera

Capture image on eye blink
Capture image on eye blinkCapture image on eye blink
Capture image on eye blinkInnovationM
 
Android RuntimePermissionsExtended
Android RuntimePermissionsExtendedAndroid RuntimePermissionsExtended
Android RuntimePermissionsExtendedNebojša Vukšić
 
Droidcon NYC 2014: Building Custom Camera Applications
Droidcon NYC 2014: Building Custom Camera ApplicationsDroidcon NYC 2014: Building Custom Camera Applications
Droidcon NYC 2014: Building Custom Camera ApplicationsHuyen Dao
 
Droidcon NYC 2014: Building Custom Camera Applications
Droidcon NYC 2014: Building Custom Camera ApplicationsDroidcon NYC 2014: Building Custom Camera Applications
Droidcon NYC 2014: Building Custom Camera ApplicationsHuyen Tue Dao
 
Introduction of Android Camera1
Introduction of Android Camera1Introduction of Android Camera1
Introduction of Android Camera1Booch Lin
 
How to create a camera2
How to create a camera2How to create a camera2
How to create a camera2Booch Lin
 
Camera2 API: Overview
Camera2 API: OverviewCamera2 API: Overview
Camera2 API: OverviewSuhyun Park
 
Building a Native Camera Access Library - Part II - Transcript.pdf
Building a Native Camera Access Library - Part II - Transcript.pdfBuilding a Native Camera Access Library - Part II - Transcript.pdf
Building a Native Camera Access Library - Part II - Transcript.pdfShaiAlmog1
 
How to implement camera recording for USB webcam or IP camera in C#.NET
How to implement camera recording for USB webcam or IP camera in C#.NETHow to implement camera recording for USB webcam or IP camera in C#.NET
How to implement camera recording for USB webcam or IP camera in C#.NETOzeki Informatics Ltd.
 
06.Programming Media on Windows Phone
06.Programming Media on Windows Phone06.Programming Media on Windows Phone
06.Programming Media on Windows PhoneNguyen Tuan
 
Skinning Android for Embedded Applications
Skinning Android for Embedded ApplicationsSkinning Android for Embedded Applications
Skinning Android for Embedded ApplicationsVIA Embedded
 
Exploring CameraX from JetPack
Exploring CameraX from JetPackExploring CameraX from JetPack
Exploring CameraX from JetPackHassan Abid
 
Android programming -_pushing_the_limits
Android programming -_pushing_the_limitsAndroid programming -_pushing_the_limits
Android programming -_pushing_the_limitsDroidcon Berlin
 
Implementation of Push Notification in React Native Android app using Firebas...
Implementation of Push Notification in React Native Android app using Firebas...Implementation of Push Notification in React Native Android app using Firebas...
Implementation of Push Notification in React Native Android app using Firebas...naseeb20
 

Similar to Camera (20)

Capture image on eye blink
Capture image on eye blinkCapture image on eye blink
Capture image on eye blink
 
Android RuntimePermissionsExtended
Android RuntimePermissionsExtendedAndroid RuntimePermissionsExtended
Android RuntimePermissionsExtended
 
Droidcon NYC 2014: Building Custom Camera Applications
Droidcon NYC 2014: Building Custom Camera ApplicationsDroidcon NYC 2014: Building Custom Camera Applications
Droidcon NYC 2014: Building Custom Camera Applications
 
Droidcon NYC 2014: Building Custom Camera Applications
Droidcon NYC 2014: Building Custom Camera ApplicationsDroidcon NYC 2014: Building Custom Camera Applications
Droidcon NYC 2014: Building Custom Camera Applications
 
Introduction of Android Camera1
Introduction of Android Camera1Introduction of Android Camera1
Introduction of Android Camera1
 
How to create a camera2
How to create a camera2How to create a camera2
How to create a camera2
 
Camera2 API: Overview
Camera2 API: OverviewCamera2 API: Overview
Camera2 API: Overview
 
Building a Native Camera Access Library - Part II - Transcript.pdf
Building a Native Camera Access Library - Part II - Transcript.pdfBuilding a Native Camera Access Library - Part II - Transcript.pdf
Building a Native Camera Access Library - Part II - Transcript.pdf
 
QXCameraKit
QXCameraKitQXCameraKit
QXCameraKit
 
How to implement camera recording for USB webcam or IP camera in C#.NET
How to implement camera recording for USB webcam or IP camera in C#.NETHow to implement camera recording for USB webcam or IP camera in C#.NET
How to implement camera recording for USB webcam or IP camera in C#.NET
 
06.Programming Media on Windows Phone
06.Programming Media on Windows Phone06.Programming Media on Windows Phone
06.Programming Media on Windows Phone
 
Skinning Android for Embedded Applications
Skinning Android for Embedded ApplicationsSkinning Android for Embedded Applications
Skinning Android for Embedded Applications
 
Android Froyo
Android FroyoAndroid Froyo
Android Froyo
 
Di code steps
Di code stepsDi code steps
Di code steps
 
Exploring CameraX from JetPack
Exploring CameraX from JetPackExploring CameraX from JetPack
Exploring CameraX from JetPack
 
Android Camera
Android CameraAndroid Camera
Android Camera
 
Android wear - watch face
Android wear - watch faceAndroid wear - watch face
Android wear - watch face
 
Android programming -_pushing_the_limits
Android programming -_pushing_the_limitsAndroid programming -_pushing_the_limits
Android programming -_pushing_the_limits
 
UIAutomator
UIAutomatorUIAutomator
UIAutomator
 
Implementation of Push Notification in React Native Android app using Firebas...
Implementation of Push Notification in React Native Android app using Firebas...Implementation of Push Notification in React Native Android app using Firebas...
Implementation of Push Notification in React Native Android app using Firebas...
 

Recently uploaded

Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsHyundai Motor Group
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetEnjoy Anytime
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 

Recently uploaded (20)

Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 

Camera

  • 1. Camera The Android framework includes support for various cameras and camera features available on devices, allowing you to capture pictures and videos in your applications. The BASICS The Android framework supports capturing images and video through the android.hardware.camera2 API or camera Intent. Here are the relevant classes: android.hardware.camera2 This package is the primary API for controlling device cameras. It can be used to take pictures or videos when you are building a camera application. Camera This class is the older deprecated API for controlling device cameras. SurfaceView This class is used to present a live camera preview to the user MediaRecorder This class is used to record video from the camera. Intent An intent action type of MediaStore.ACTION_IMAGE_CAPTURE or Med iaStore.ACTION_VIDEO_CAPTURE can be used to capture images or videos without directly using the Camera object. Creating a new project Open your Android Studio and create a new blank activity application. The first step is to add the android permissions and required features. Add these lines to your AndroidManifest.xml: <uses-permission android:name="android.permission.CAMERA" /> <uses-feature android:name="android.hardware.camera" /> Inside your style.xml, just edit the line to remove the ActionBar, if you prefer(this is removed just to have a full-screen camera): <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar"> Create this basic activity_main.xml: <FrameLayout xmlns:android="http://schemas.android.com/apk/re s/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <FrameLayout android:id="@+id/camera_view" android:layout_width="match_parent" android:layout_height="match_parent"> </FrameLayout> <ImageButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/imgClose" android:layout_gravity="right|top" android:background="@android:drawable/ic_menu _close_clear_cancel" android:padding="20dp"/> </FrameLayout> Here we have a simple FrameLayout. The camera_view will display the camera data, that we’ll use later with OpenGL and some algorithms to process it. And the ImageButton will be used to close the application. III - Camera code The first step is to create a SurfaceView. It’ll receive camera data and display it inside the FrameLayout. Create a new file, CameraView.java in the same folder that your MainActivity.java is.
  • 2. First, just extend the SurfaceView and implements the SurfaceHolder.Callback. You’ll have something like this code: public class CameraView extends SurfaceView implements SurfaceHolder.Callback{ public CameraView(Context context, Camera camera){ super(context); } @Override public void surfaceCreated(SurfaceHolder surfaceHolder) { } @Override public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i2, int i3) { } @Override public void surfaceDestroyed(SurfaceHolder surfaceHolder) { } } Add these two private variables: private SurfaceHolder mHolder; private Camera mCamera; And then just update your CameraView constructor with: public CameraView(Context context, Camera camera){ super(context); mCamera = camera; mCamera.setDisplayOrientation(90); //get the holder and set this class as the callback, so we can get camera data here mHolder = getHolder(); mHolder.addCallback(this); mHolder.setType(SurfaceHolder.SURFACE_TYPE _NORMAL); } Now, override these methods, I commented everything to help you: @Override public void surfaceCreated(SurfaceHolder surfaceHolder) { try{ //when the surface is created, we can set the camera to draw images in this surfaceholder mCamera.setPreviewDisplay(surfaceHolder); mCamera.startPreview(); } catch (IOException e) { Log.d("ERROR", "Camera error on surfaceCreated " + e.getMessage()); } } @Override public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i2, int i3) { //before changing the application orientation, you need to stop the preview, rotate and then start it again if(mHolder.getSurface() == null)//check if the surface is ready to receive camera data return; try{ mCamera.stopPreview(); } catch (Exception e){ //this will happen when you are trying the camera if it's not running } //now, recreate the camera preview try{ mCamera.setPreviewDisplay(mHolder); mCamera.startPreview(); } catch (IOException e) { Log.d("ERROR", "Camera error on surfaceChanged " + e.getMessage()); } } @Override public void surfaceDestroyed(SurfaceHolder surfaceHolder) { //our app has only one screen, so we'll destroy the camera in the surface //if you are unsing with more screens, please move this code your activity mCamera.stopPreview(); mCamera.release(); } III - Camera Activity Now, inside you MainActivity.java, add these variables:
  • 3. private Camera mCamera = null; private CameraView mCameraView = null; No, override the method bellow, I commented to help you to understand it: protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); try{ mCamera = Camera.open();//you can use open(int) to use different cameras } catch (Exception e){ Log.d("ERROR", "Failed to get camera: " + e.getMessage()); } if(mCamera != null) { mCameraView = new CameraView(this, mCamera);//create a SurfaceView to show camera data FrameLayout camera_view = (FrameLayout)findViewById(R.id.camera_view); camera_view.addView(mCameraView);//add the SurfaceView to the layout } //btn to close the application ImageButton imgClose = (ImageButton)findViewById(R.id.imgClose); imgClose.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { System.exit(0); } }); } Now, you can run your app.