1. Create an empty project, and notice the following permissions:
<android:name= "Android.permission.CAMERA"/>< android:name= "Android.permission.WRITE_EXTERNAL_STORAGE"/>
2. layout file
<?XML version= "1.0" encoding= "Utf-8"?><Framelayoutxmlns:android= "Http://schemas.android.com/apk/res/android"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent"> <SurfaceviewAndroid:id= "@+id/surfaceview"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent"/></Framelayout>
Very simply, put a surfaceview to display the video image.
3. Initialize the camera
Private void Initcamera () { = camera.open ();}
Using the camera's open method, the Open method also has an overloaded method, which is mainly used to tell the system which camera I want to open, and now the phone is usually more than two camera heads. The rear camera is turned on by default.
4. Release the camera
Private void Releasecamera () { ifnull) { // stop preview before releasing Camera.setpreviewcallback (null); Camera.stoppreview (); Camera.release (); NULL ; }}
Here are some of the more important methods, the following is the code for the entire activity:
Public classMainactivityextendsappcompatactivity{Privatecamera camera; PrivateSurfaceview Surfaceview; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R.layout.activity_main); Surfaceview=(Surfaceview) Findviewbyid (R.id.surfaceview); } @Overrideprotected voidOnStart () {Super. OnStart (); Initcamera (); Surfaceview.getholder (). Addcallback (NewSurfaceholder.callback () {@Override Public voidsurfacecreated (Surfaceholder holder) {Holder.removecallback ( This); Try{camera.setpreviewdisplay (holder); Camera.startpreview (); } Catch(IOException e) {e.printstacktrace (); }} @Override Public voidSurfacechanged (Surfaceholder holder,intFormatintWidthintheight) {} @Override Public voidsurfacedestroyed (Surfaceholder holder) {}}); } @Overrideprotected voidOnStop () {Super. OnStop (); Releasecamera (); } Private voidInitcamera () {camera=Camera.open (); } Private voidReleasecamera () {if(Camera! =NULL) { //Stop preview before releasingCamera.setpreviewcallback (NULL); Camera.stoppreview (); Camera.release (); Camera=NULL; } }}
It is worth mentioning that the camera's Startpreview method needs to be called after Surfaceviewholder is created, otherwise the video image will not be displayed in Surfaceview.
This article is a demo download.
Android video recording never getting started to the Getting Started Series tutorial (ii) ———— display video images