Android Camera Application Development Example

Source: Internet
Author: User

  Before learning to get photos directly from the local camera, I think it's best to develop a simple camera based on the Android-given camera API and have a basic understanding of how the camera works.

  First step, set up Surfaceview display preview (before taking photos)

The Activity_main.xml file defines the Framelayout layout and uses a button to implement the photo behavior

  

<Framelayoutxmlns: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 "    >    <SurfaceviewAndroid:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:id= "@+id/surfaceview"android:layout_gravity= "Center" />    <RelativelayoutAndroid:layout_width= "Match_parent"Android:layout_height= "Match_parent"android:visibility= "visible"Android:id= "@+id/shot_button_layout"        >        <ButtonAndroid:id= "@+id/button"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:layout_alignparentright= "true"Android:layout_alignparentbottom= "true"Android:text= "@string/shot"Android:layout_marginright= "10DP"Android:layout_marginbottom= "10DP"/>        </Relativelayout></Framelayout>

  OnCreate method Layout Full screen and add callback function, where button click action to take a photo

@Overrideprotected voidonCreate (Bundle savedinstancestate) {requestwindowfeature (window.feature_no_title);//This method must be called before the Super.oncreate method        Super. OnCreate (savedinstancestate); GetWindow (). SetFlags (WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN );//Full Screen displaySetcontentview (R.layout.activity_main); Button=(Button) Findviewbyid (R.id.button); Button.setonclicklistener (NewView.onclicklistener () {@Override Public voidOnClick (View v) {mcamera.takepicture (NULL,NULL,Newmypicturecallback ());        }        }); Msurfaceview=(Surfaceview) Findviewbyid (R.id.surfaceview);        Msurfaceview.getholder (). SetType (Surfaceholder.surface_type_push_buffers); //Get phone resolutionDisplay display = Getwindowmanager (). Getdefaultdisplay ();//Activity#getwindowmanager ()Point size =NewPoint ();        Display.getsize (size);        Msurfaceview.getholder (). Setfixedsize (SIZE.X,SIZE.Y); Msurfaceview.getholder (). Setkeepscreenon (true); Msurfaceview.getholder (). Addcallback (Newsurfacecallback ()); }

  One important step is to handle the display and update of the Surfaceview.

Private Final classSurfacecallbackImplementssurfaceholder.callback{@Override Public voidsurfacecreated (Surfaceholder holder) {Mcamera=Camera.open (); Camera.parameters Parameters=mcamera.getparameters (); Msupportedpreviewsizes=parameters.getsupportedpreviewsizes (); Camera.size mpreviewsize= Msupportedpreviewsizes.get (Msupportedpreviewsizes.size ()-1);            Parameters.setpreviewsize (Mpreviewsize.width,mpreviewsize.height); Parameters.setpreviewframerate (5); if(Parameters.getsupportedpreviewformats (). Contains (Imageformat.jpeg)) {Parameters.setpreviewformat (Image            FORMAT.JPEG);            } parameters.setpictureformat (Imageformat.jpeg); Parameters.setpicturesize (1024, 768); Parameters.setjpegquality (80);            Mcamera.setparameters (parameters); Try{mcamera.setpreviewdisplay (holder);            Mcamera.startpreview (); } Catch(IOException e) {e.printstacktrace (); } log.v (Log_tag,"Camera parameters is:" +Parameters.flatten ()); } @Override Public voidSurfacechanged (Surfaceholder holder,intFormatintWidthintheight) {} @Override Public voidsurfacedestroyed (Surfaceholder holder) {if(Mcamera! =NULL) {mcamera.release (); Mcamera=NULL; }        }    }

   

   The second step is to save the photo and photograph data (stored in the camerademo/directory in the SD card).

Private Final class Implements camera.picturecallback {        @Override        publicvoid onpicturetaken (byte [] data, camera camera) {            new  savepicturetask ();            Savepicturetask.execute (data);              Mcamera.startpreview ();        }    }

  set up in the upper code Savepicturetask asynchronous Processing class.

 Public classSavepicturetaskextendsasynctask<byte[],void,void>{@OverrideprotectedVoid Doinbackground (byte[] ... params) {File path=NewFile (Getsdpath () + "/camerademo"); if(!path.exists ())        {Path.mkdirs (); }        //Create a fileCalendar Calendar =calendar.getinstance (); String filename= "" +calendar.get (calendar.year) +calendar.get (calendar.month) +calendar.get (calendar.day_of_month)+integer.tostring ((int) System.currenttimemillis ()) + ". jpg"; File Picture=NewFile (path+ "/" +filename);//This is the full path .        Try{FileOutputStream out=NewFileOutputStream (picture); Out.write (params[0]);        Out.close (); } Catch(Exception e) {e.printstacktrace (); }        return NULL; }     PublicString Getsdpath () {File Sddir=NULL; BooleanSdcardexist =environment.getexternalstoragestate (). Equals (Android.os.Environment.MEDIA_MOUNTED); //determine if the SD card exists        if(sdcardexist) {Sddir= Environment.getexternalstoragedirectory ();//Get with directory        }        returnsddir.tostring (); }}

  A camera that implements a simple photo-taking function is not very difficult, but the pattern given to the API needs to be further understood. The autofocus function of this camera is not very good, need to be improved, there is no code, the future needs to study deeply. The full code will be posted when I update to GitHub.

Android Camera Application Development Example

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.