"Android App Development technology: Media Development" video

Source: Internet
Author: User

Guo Xiaoxing
Weibo: Guo Xiaoxing's Sina Weibo
Email:[email protected]
Blog: http://blog.csdn.net/allenwells
Github:https://github.com/allenwells

One enable camera 1.1 request camera permissions
... >    <uses-feature android:name="android.hardware.camera"                  android:required="true" />    ...</manifest>

If our app uses a camera, but the camera is not an essential component of the app's normal operation, you can set the android:required to False. That way, Google play will also allow devices without a camera to download the app. Of course it is necessary before using the camera by calling the following methods:

hasSystemFeature(PackageManager.FEATURE_CAMERA);

To check if there is a camera on the device. If not, we should disable the camera-related features.

1.2 Creating a Intent Object

Using a Intent object that describes what to do, Android can delegate certain execution tasks to other applications. The whole process consists of three parts:

    • Intent itself
    • A function call to start the external Activity
    • When the focus returns to your activity, the code that returns the image data is processed.

Example

Send a intent to record a video

staticfinalint1;privatevoiddispatchTakeVideoIntent() {    new Intent(MediaStore.ACTION_VIDEO_CAPTURE);//注意在调用startActivityForResult()方法之前,先调用resolveActivity(),这个方法会返回能处理该Intent的第一个Activity,即即检查有没有能处理这个Intent的Activity。执行这个检查是必要的,因为如果你调用startActivityForResult()时,没有应用能处理该Intent,应用将会崩溃。所以只要返回结果不为null,使用该Intent就是安全的。    ifnull)     {        startActivityForResult(takeVideoIntent, REQUEST_VIDEO_CAPTURE);    }}
1.3 Viewing video

The Android Camera program adds a URI that points to the video storage address to the intent and transmits it to the Onactivityresult ()) method.

Example

Get the video and show it to a videoview.

@OverrideprotectedvoidonActivityResult(intint resultCode, Intent data) {    if (requestCode == REQUEST_VIDEO_CAPTURE && resultCode == RESULT_OK) {        Uri videoUri = intent.getData();        mVideoView.setVideoURI(videoUri);    }}
Two control camera 2.1 open Camera object

Getting a camera object is the first step in direct control of the cameras. Just like the camera program that comes with Android, the way to access the camera is to open the camera with another thread inside the OnCreate ()) method. This approach can be avoided because the UI thread is blocked because of a longer boot time. There is also a better way to defer the operation of the camera opening to the Onresume ()) method, which makes the code easier to reuse and keeps the control process simple.

Private Boolean Safecameraopen(intID) {Booleanqopened =false;Try{Releasecameraandpreview ();        Mcamera = Camera.open (ID); qopened = (Mcamera! =NULL); }Catch(Exception e) {LOG.E (getString (R.string.app_name),"failed to open Camera");    E.printstacktrace (); }returnqopened; }Private void Releasecameraandpreview() {Mpreview.setcamera (NULL);if(Mcamera! =NULL) {mcamera.release (); Mcamera =NULL; }}
2.2 Creating the Camera Preview interface

Taking pictures usually requires a preview interface for the user to display the objects to be photographed, and we can use Surfaceview to show the images captured by the camera.

//In order to display a preview interface, we need to create an previews class. This class needs to implement the Android.view.SurfaceHolder.Callback interface, which uses this interface to pass the data acquired by the camera hardware to the program, which must be passed to the camera object before the image real-time preview begins.  class Preview extends viewgroup implements Surfaceholder. Callback {Surfaceview Msurfaceview;    Surfaceholder Mholder; Preview (Context context) {Super(context); Msurfaceview =NewSurfaceview (context); AddView (Msurfaceview);//Install a surfaceholder.callback so we get notified when the        //Underlying surface is created and destroyed.Mholder = Msurfaceview.getholder (); Mholder.addcallback ( This);    Mholder.settype (surfaceholder.surface_type_push_buffers); }...}

After preview is created, we can then set up and launch preview. The preview of the camera instance associated with it must be created in a specific order, where the camera object is first created.

Example

Encapsulates the action of initializing CanEra

 Public void Setcamera(Camera camera) {if(Mcamera = = camera) {return;    } stoppreviewandfreecamera (); Mcamera = camera;if(Mcamera! =NULL) {list<size> localsizes = Mcamera.getparameters (). getsupportedpreviewsizes ();        msupportedpreviewsizes = localsizes; Requestlayout ();Try{Mcamera.setpreviewdisplay (Mholder); }Catch(IOException e)        {E.printstacktrace (); }//Important:call Startpreview () to start updating the preview        //surface. Preview must is started before you can take a picture.Mcamera.startpreview (); }}
2.3 Modifying Camera settings

Camera settings can change the way you take pictures.

Example

Change the preview size as follows:

public   void  surfacechanged  (surfaceholder holder, int  format, int  W, int  h) {//Now" the size is known, set up the camera parameters and begin  //the    Preview.     Camera.parameters Parameters = Mcamera.getparameters ();    Parameters.setpreviewsize (Mpreviewsize.width, mpreviewsize.height);    Requestlayout ();    Mcamera.setparameters (parameters);    //important:call Startpreview () to start updating the preview surface.     //Preview must be started before you can take a picture.  Mcamera.startpreview ();}  

Most camera programs lock the preview as a horizontal screen, because that direction is the natural direction of the camera sensor. Of course, this setting does not prevent the portrait from taking pictures, as the orientation information of the device is recorded in the EXIF header. The Setcameradisplayorientation ()) method allows you to change the orientation of the preview without affecting the photo shooting process. However, for systems with Android API level 14 and below, you must stop the preview before changing the direction before restarting it.

2.4 Taking photos

After the preview starts, you can take a photo.

Take a Photo: Call Camera.takepicture () and pass the created Camera.picturecallback and Camera.shuttercallback object inside the method.

Take photos continuously: Call Camera.takepicture (), create a camera.previewcallback and implement the Onpreviewframe () method. We can either shoot the selected preview frame or create a delay for calling Takepicture ()).

After you have taken a good picture, you must restart the preview before the user takes the next picture.

Example

Use the shutter to reboot, as shown below:

@OverridepublicvoidonClick(View v) {    switch(mPreviewState) {    case K_STATE_FROZEN:        mCamera.startPreview();        mPreviewState = K_STATE_PREVIEW;        break;    default:        nullnull);        mPreviewState = K_STATE_BUSY;    // switch    shutterBtnConfig();}
2.5 Stop previewing and releasing the camera

When the program is finished using the camera, it is necessary to do the cleanup action. In particular, the camera object must be released, otherwise it may cause other apps to crash, including new instances of our own application. After the previewed surface is destroyed, you can stop the preview and release the camera's action.

 Public void surfacedestroyed(Surfaceholder Holder) {//Surface would be destroyed if we return, so stop the preview.    if(Mcamera! =NULL) {//Call Stoppreview () to stop updating the preview surface.Mcamera.stoppreview (); }}/** * When the This function returns, Mcamera would be null. */Private void Stoppreviewandfreecamera() {if(Mcamera! =NULL) {//Call Stoppreview () to stop updating the preview surface.Mcamera.stoppreview ();//Important:call release () to release the "Camera for use"        //Applications. Applications should release the camera immediately        //During onPause () and re-open () it during Onresume ()).Mcamera.release (); Mcamera =NULL; }}

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

"Android App Development technology: Media Development" video

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.