Android Custom Camera Super detailed explanation
Reprint please indicate source: http://blog.csdn.net/vinicolor/article/details/49642861;
Since the online article about the Android custom camera is not too detailed, Google's official documentation is not very easy to understand, so let me explain the Android custom camera in detail today.
This article is mainly for some people who have just contacted Android to see the official API difficulties and do not know much about the android mechanism of the students, so skilled developers can bypass.
Recently in the use of camera class found incredibly abandoned, API 21 appeared in Camera2 this class to replace the camera class, but the author's cell phone Andorid 4.4, the domestic to use 6.0 at least next year, so this time or to explain camera this class.
The first is to join the permissions, this directly follow the Google API Wizard or the API documentation will be detailed, so this is not said.
So next, using the camera we always need a place where we can see the image, and here Google calls us to use the Surfaceview class, so what's the Surfaceview class, first of all, this class is inherited view, you can draw the image on the screen and display it to the user. The reason I can actually show this is that Surfaceview contains a surface object, and surface is a visible part of Surfaceview, so we're talking about surface, and it's a concept that makes a lot of people headache, okay, let's start over.
The first thing we see on the phone screen is that these images are view (of course surfaceview), so what is view? View is actually a small area of cell phone memory, the so-called display, is the graphics card and other hardware to display the memory of the information on the screen process, I think we should be clear about it, we continue, then we say the visible part of what is going on, actually we see the screen can be said to be 2-dimensional, that is, the length , but in its internal is actually 3-dimensional, there is a dimension is layer layers, that is, the concept of layer, with Visio or AutoCAD students should be very well understood, in the drawing, the upper layer will sometimes be the underlying occlusion, we see the image is such a layer of stacking up, Some of these layers are not visible, some layers are visible, some layers are completely visible, and what we see is the visible part of them, and surface is a visible part of the Surfaceview, which is what we use to photograph or photograph.
Understanding the role of view, I think someone will ask: Why not use view, and with Surfaceview, first here I want to say with view this is possible, but with Surfaceview will be better, In Surfaceview, Google has rewritten a number of methods for camera methods, and the Surfaceview class is redrawing the screen in a new, separate thread, and view is drawing the screen on the UI thread, which you can imagine, If you use view to preview an image (of course you have to rewrite a lot of methods in view to achieve a preview, which we do not want to see), then you do not want to do anything in the video, because if you plan to update the UI, the thread may block, your app may not respond, The Android system automatically prompts off, which is a very bad experience for the user, and we want to be able to update the UI in the camera, so we use the Surfaceview class to preview the image.
Next we look at the official code for US:
PublicClassCamerapreviewExtendsSurfaceviewImplementsSurfaceholder.Callback {Private Surfaceholder Mholder;Private Camera Mcamera;PublicCamerapreview (context context, camera camera) {Super (context); Mcamera = camera;Install a surfaceholder.callback so we get notified when theUnderlying surface is created and destroyed. Mholder = Getholder (); Mholder.addcallback (this);Deprecated setting, but required on Android versions prior to 3.0 Mholder.settype (Surfaceholder.surface_type_push_buff ERS); }PublicvoidSurfacecreated (Surfaceholder holder) {The Surface has a been created, now tell the camera where to draw the preview.try {mcamera.setpreviewdisplay (holder); Mcamera.startpreview ();}catch (IOException e) {log.d (TAG,"Error setting Camera Preview:" + e.getmessage ());}}PublicvoidSurfacedestroyed (Surfaceholder holder) {Empty. Take care of releasing the Camera preview in your activity. }PublicvoidSurfacechanged (Surfaceholder holder,int format,int W,int h) {If your preview can change or rotate, take care of the those events here.Make sure to stop the preview before resizing or reformatting it.if (mholder.getsurface () = = null) { //preview surface does not exist return;} //Stop preview before making changes try {mcamera.stoppreview ();} catch (Exception e) { //ignore:tried to stop a non-existent preview} //Set preview size and do any resize , rotate or/ /reformatting changes here //Start preview with new settings try {mcamera.setpreviewdisplay ( Mholder); Mcamera.startpreview (); } catch (Exception e) {log.d (TAG, "Error starting Camera preview:" + e.getmessage ()); }}}
First of all, do not forget the most important thing: is to get the camera instance, or will definitely report null pointer exception, we use the Camera.open () method to obtain the instance object, for Andorid 2.3 before the phone is actually no front-facing camera, so direct camera.open () method on the line, but after the version of the phone has a front-facing camera, so the phone has two cameras, then Camera.open () can not clearly indicate the end of the camera, so Google provides the Camera.open (0) method, This method actually refers to the rear camera with the phone, and the front camera uses the Camera.open (1) method so that the camera object can be obtained.
It is important to note that Android cameras can only be bound by an app thread because of Android, which means that if you are using a camera to take a photo, another program cannot use the camera class to enable it, and will report the can not Release of the error, then how to determine whether you use the camera, in fact, as long as you use the Camera.open () method to obtain a camera example, the system thinks you use the camera, so when you use the camera must remember to release the camera resources, Otherwise the application does not use Ah, we can use Camera.release () to release the camera resources, Google's official opinion is to rewrite the activity of the OnPause () method to Camera.release (), You can also rewrite the activity's onbackpressed () method to release the camera, which is when the user presses the back key to release the camera resource.
Look at the above story we know that surface is actually a corresponding memory area, and the memory area of the data has a life cycle, Can be dynamically requested to create and destroy, of course, will also update, so there is the operation of the memory area, in this case is surfacecreated/changed/destroyed, that is, create/modify/Destroy, and 3 operations together is callback.
surface code requires US implements Surfaceholder.callback, so why use Surfaceholder.callback, Callback meaning callback, then why does it have to callback it? Here I explain the callback, the callback in most cases is that the program is running to need a function (but it does not itself) here is the program needs to look at its internal records can handle the situation of the function, borrowed from the internet analogy: a person has the ability to do something but now don't do it, So he went to register his ability, to need to use him, he will be called to do, into the program is a person can do surfacecreated/changed/destroyed 3 things, he went to register, And there is a collectively called surfaceholder.callback, and in this procedure need to do these 3 things, so will Callback. And Surfaceholder is what, it is like with the developer in this example, and Surfaceview is a building plan for the owner, it knows to first to find developers, so Mholder = Getholder () to find developers, And developers can find a building capacity of this person A, is to callback his registered information Mholder.addcallback (this), and A's ability can be likened to surfacecreated House, surfacedestroyed demolition Houses, Surfacechanged decorate the house, so the name thought, surfacechanged only in the building and demolition room between.
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
This is to set the cache information for Mholder, which is automatically set after Android 3.0, so we can ignore this code.
well to surfacecreated, this is when the screen was created, we need to bind the camera's preview interface to our visible area Surfaceview, and Getholder () The resulting holder is absolute control of surface, so we used holder, which is to connect Surfaceview to camera and prepare a real-time camera Image preview interface.
mCamera.setPreviewDisplay(holder);
Next, you can set the start preview
mCamera.startPreview();
of course, don't be happy, this is not finished, the program after the execution of surfacecreated is bound to execute surfacechanged, this method means that as long as the screen changes will call a it, Surfacecreated is called when the program is first started, and then once surfacechanged is called, so the Surfacechanged method must be called at least once during the entire use of the camera. So we usually in the Surfacechanged method to determine the visible area surface is normal, but also control when the interface changes when the camera changes, such as the change of the camera when the screen switch, the following code we should be able to understand, In fact, when the surface changes detected when the detection surface is normal, all the steps are to stop the camera preview, and then according to surface changes, change the camera's related properties, and then as described in the above Surfacechanged method mCamera.setPreviewDisplay(mHolder) and mCamera.startPreview() You can start the preview.
One thing to say: If you want to use a series of features like camera autofocus and flash, you can also set it up in the Surfacechanged method, where a small amount of code is posted:
Camera.Parameters params = mCamera.getParameters();List<String> focusModes = params.getSupportedFocusModes(); if(focusModes.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)) {params.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);}mCamera.setParameters(params);
The main thing is to first determine whether the phone has this function focusmodes.contains (), and then set this function Params.setfocusmode (), more features can be in the API Camera.parameters class to view and use.
we can take pictures.
Next we should take a picture, then face how to store the picture problem, in fact, Google provides the Mcamera.takepicture () method, this method has 3 parameters, as follows:
takePicture (Camera.ShutterCallback shutter, Camera.PictureCallback raw, Camera.PictureCallback jpeg)
The first two parameters camera.shuttercallback is in the snapshot of the instant callback, can be used to add a picture of the sound or the like, or after the camera preview to the user to see, ask whether it is necessary to retain, Camera.picturecallback is to return a native image data, these two parameters in fact in the normal Use is not practical (if you want to preview we can also use the data in Camera.picturecallback to preview), so we set NULL means no, Camera.picturecallback This is what we need, it is to return a compressed JPEG file, just right for our daily use, so we choose this method, the specific code is as follows:
public void onClick(View v) { switch (v.getId()) { case R.id.button_capturePicture:mCamera.takePicture(null, null, new Camera.PictureCallback() { @Overridepublic void onPictureTaken(byte[] data, Camera camera) { } });
Well, in fact, this code is more obvious, Onpicturetaken is Andorid automatic callback method, the data parameter in the Onpicturetaken method is to obtain the image of the information, only need an output stream to write data to the external storage on the line, Here the output of the data is not explained in detail. When calling Takepicture, the camera automatically stops previewing, that is, the image is stopped, and we can start the preview again in the rewrite callback function Onpicturetaken:
mCamera.startPreview();
It's time to video:
The code of photography is a little more troublesome, we need to use Mediarecorder this class, first we get an example:
Mmediarecorder = new Mediarecorder ();
for the use of cameras we need to unlock the camera: Mcamera.unlock ();
So what exactly do we need to unlock the camera? The original camera after we used the Camera.open (), is bound to the process of the program, then the other process will not be able to access, that is, we need to record images and sound of the Mediarecorder class can not use the camera, so we need to unlock , so that the camera can be used by the Mediarecorder class, this unlock is temporary, after use (that is, after the camera is completed) we can reconnect () method to let the camera reconnect to our previous program process, Of course, the unlock mechanism of the camera after Android 4.0 we do not need to manually unlock, Andorid will automatically help us to complete.
Next we can use Mediarecorder to connect the camera:
Mmediarecorder.setcamera (Mcamera);
below we need to set some resources for the camera:
mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER); mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);mMediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH)); mMediaRecorder.setOutputFile(getOutputMediaFile(MEDIA_TYPE_VIDEO).toString());
Setaudiosource is set in the camera to obtain sound components, camcorder is roughly the camera's acoustic components bar, of course, we can also use mic instead, that is, the phone's microphone, Setvideosource is to set the camera to obtain the image of the component, This is no objection, it must be camera, then Mmediarecorder.setprofile (Camcorderprofile.get (Camcorderprofile.quality_high)), This is the configuration file that sets the camera, reads the Setaudiosource and Setvideosource properties that are set in front, assigns to us the audio and video, and sets the quality of the recording, So this method has to be called after the Setaudiosource and Setvideosource methods, otherwise it will go wrong. Okay, now we're going to specify where we put the recorded files, the Setoutputfile () method is where the settings are placed, we need to pass an address parameter to it, that is, the address string, note that the address needs to add the extension name such as. mp4 (actually on Android Before 2.2 we needed Setoutputformat () to format it, but then Android would automatically do it for us.
All right, we're all done with the preparation (many of you will definitely scold this for a lot of code to get the job done-_-), we call the Mmediarecorder.prepare () method to let Android help us detect the previous settings right, so we need to catch the exception OH
mMediaRecorder.prepare();
Our camera data Android will automatically help us to store the path we give.
Ready to finish, let's start filming!
mMediaRecorder.start();
Of course, if you want to stop the camera, remember to use the Stop () method mMediaRecorder.stop(); first.
Then release the system resources that Mmediarecorder occupies:
if (mMediaRecorder != null) { mMediaRecorder.reset(); mMediaRecorder.release(); mMediaRecorder = null; mCamera.lock(); }
Mmediarecorder.reset () is to reset your mmediarecorder configuration information, Mmediarecorder.release () is to release the resources occupied by Mmediarecorder, of course, we previously unlocked the camera, This time since we don't have to take a video, we'll lock it in Mcamera.lock (), but remember that if you still want a photo or another camera, don't call Camera.release () to release the camera's resources, or your preview will close immediately. If you want to re-camera, repeat the preparation steps above, then start () on the line.
Android Custom Camera Super detailed explanation