Android development tutorial on the method of calling the camera function detailed _android

Source: Internet
Author: User
Tags dateformat locale stub

This example describes the way Android calls the camera feature. Share to everyone for your reference, specific as follows:

We're going to call the camera's photo function, apparently

The first step must join the call to the camera hardware permissions , after the photo we want to save the picture in the SD card, must add SD card read and write permission, so the first step, we should add the following code in the Android listing file

Camera Privileges:

<uses-permission android:name= "Android.permission.CAMERA"/>

SD card Read and Write permission:

<uses-permission android:name= "Android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<uses-permission Android:name= "Android.permission.WRITE_EXTERNAL_STORAGE"/>

The second step is to display the image captured by the camera in real time on the phone.

We implemented this view component with Surfaceview, so add the following code to the Main.xml

<surfaceview
  android:layout_width= "fill_parent"
  android:layout_height= "Fill_parent"
  android: Id= "@+id/surfaceview"
 />

Step three, set how the window is displayed

Get the current window first

windows window = GetWindow ();

Then set no title

Requestwindowfeature (window.feature_no_title);//No title

Then set the full screen

Copy Code code as follows:
Window.setflags (WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);//Set Full screen

Of course, during the photo shoot, the screen must be in a consistent state of highlighting, so add the following code

Copy Code code as follows:
Window.addflags (WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);//Set highlighting

At this point, we have specified the window's display as dead, before we can set the components displayed on the window (order is very important)

Setcontentview (R.layout.main);

Step fourth, set the properties of the Surficeview display control

Find Surficeview

Surfaceview = (Surfaceview) Findviewbyid (R.id.surfaceview);

Set its pixel to 800x600

Surfaceview.getholder (). Setfixedsize (a);
The following setting Surfaceview does not maintain its own buffer, but instead waits for the screen's render engine to push content to the user
Surfaceview.getholder (). SetType (Surfaceholder.surface_ Type_push_buffers);

The fifth step is to add a callback method for Surficeview (CallBack)

Surfaceview.getholder (). Addcallback (New Surfacecallback ());

The callback class above is our own definition, and the code is as follows

Private class Surfacecallback implements surfaceholder.callback{@Override public void surfacecreated (Surfaceholder Holder) {try {camera = Camera.open ();//Turn on the hardware camera, when the guide bag must pay attention to is the Android.hardware.Camera windowmanager wm = (WindowManager)
Getsystemservice (Context.window_service)//Get the window Manager display display = Wm.getdefaultdisplay ();//Get the current screen Camera.parameters Parameters = camera.getparameters ()//Get Camera Parameters Parameters.setpreviewsize (Display.getwidth (), Display.getheight ())//Set the size of the preview photo parameters.setpreviewframerate (3);/Set 3 frames per second Parameters.setpictureformat ( PIXELFORMAT.JPEG)//Set the format of the photo parameters.setjpegquality (85);//Set the quality of the photo Parameters.setpicturesize (Display.getheight (
), Display.getwidth ())//Set the size of the photo, by default it is as big as the screen camera.setparameters (parameters); Camera.setpreviewdisplay (Surfaceview.getholder ())///Surfaceview Display frame Camera.startpreview ()/start Preview IsPreview =
true;//set whether the parameter is preview true} catch (IOException e) {log.e (TAG, e.tostring ());} @Override public void surfacechanged (surfaceholder holder, int formAt, int width, int height) {//TODO auto-generated a stub} @Override public void surfacedestroyed (Surfaceholder hol

 Der) {if (camera!=null) {if (Ispreview) {//If preview Camera.stoppreview (); Camera.release ();}}}}

Sixth step, we must monitor the key events, such as camera or focus , the code is as follows

public boolean onKeyDown (int keycode, keyevent event) {//Handle key event
if (camera!=null&&event.getrepeatcount () = =0)//represents only a click
{
switch (keycode) {
case keyevent.keycode_back://if it is a search key
   camera.autofocus (NULL); Auto focus break
 ;
  Case keyevent.keycode_dpad_center://If it is a middle key
   camera.takepicture (null, NULL, New Takepicturecallback ()); To the third object, the Takepicturecallback () is defined by itself, break in the following code
 ;
}
Return true;//prevents the event from being passed, otherwise pressing the search key becomes the system default
}

Private Final class Takepicturecallback implements picturecallback{public
void Onpicturetaken (byte[) data, Camera camera) {
try {
Bitmap Bitmap = bitmapfactory.decodebytearray (data, 0, data.length);
File File = new file (Environment.getexternalstoragedirectory (), System.currenttimemillis () + ". jpg");
FileOutputStream outputstream = new FileOutputStream (file);
Bitmap.compress (Compressformat.jpeg, outputstream);
Outputstream.close ();
Camera.stoppreview ();
Camera.startpreview ()///After processing data, you can preview
the catch (Exception e) {
log.e (TAG, e.tostring ());}
}


Note that there are two callback classes in the code, one is Surfacecallback (), and the other is Takepicturecallback (), which may be difficult for beginners to understand, in layman's terms, The former is used to monitor the display control of Surficeview, which temporarily holds picture data, to invoke different methods according to its display, including surfacecreated (), surfacechanged (), surfacedestroyed (), It is not difficult to understand why there are three callback methods (note that the camera must be released in the Surfacedestroyed () method, detailed code see above). Takepicturecallback () is the interface designed to monitor whether or not to take photos, and there is only one way to camera the data that will be taken from the camera, and we can further process the data from the camera.

At this point, a simple photo function introduction finished!

Package CN.CAMERA.RXM;
Import Java.io.File;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import Java.util.Calendar;
Import Java.util.Locale;
Import Org.apache.commons.logging.Log;
Import Android.text.format.DateFormat;
Import android.util.*;
Import android.app.Activity;
Import Android.content.Context;
Import Android.graphics.Bitmap;
Import Android.graphics.Bitmap.CompressFormat;
Import Android.graphics.BitmapFactory;
Import Android.graphics.PixelFormat;
Import Android.hardware.Camera;
Import Android.hardware.Camera.PictureCallback;
Import Android.os.Bundle;
Import android.os.Environment;
Import Android.view.LayoutInflater;
Import Android.view.Menu;
Import Android.view.MenuItem;
Import Android.view.SurfaceHolder;
Import Android.view.SurfaceView;
Import Android.view.View;
Import Android.view.View.OnClickListener;
Import Android.widget.Button;
Import Android.widget.Toast;
public class Mycamactivity extends activity {private Preview Mpreview; private Camera Mcamera; BitMap Camerabitmap;
Surfaceholder Mholder;
private static final int option_snapshot = 0;
private static final int option_stopcamera = 1;
  Private View Viewstart;
    @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
    Layoutinflater flater = This.getlayoutinflater ();
    Viewstart = flater.inflate (R.layout.main, NULL);
    Setcontentview (Viewstart);
    Button btn1 = (button) Findviewbyid (R.id.button1); Btn1.setonclicklistener (New Onclicklistener () {public void OnClick (View v) {Mpreview = new Preview (Getbasecon
    Text ());
    Setcontentview (Mpreview);
    };
  }
    ); public boolean Oncreateoptionsmenu (Menu menu) {//Menu.add (0, option_snapshot, 0, R.string.take);//menu.add (0, Optio
N_stopcamera, 1, r.string.back);
return True;//super.oncreateoptionsmenu (menu); public boolean onoptionsitemselected (MenuItem Item) {//int itemId = Item.getitemid ();//switch (itemId) {case option_s Napshot://Taking photos mcamera.takepicTure (null, NULL, jpegcallback); try {thread.sleep (4000);} catch (Interruptedexception e) {//TODO auto-generated catch block E.printstacktrace ();
Mera.startpreview ();
Break
Case option_stopcamera:mpreview = null;
Setcontentview (Viewstart);
Break
return true; Private Picturecallback Jpegcallback = new Picturecallback () {//public void Onpicturetaken (byte[] data, Camera Camera)
{try {String name = new DateFormat (). Format ("Yyyymmdd_hhmmss", Calendar.getinstance (Locale.china)) + ". jpg";
FileOutputStream fileout = new FileOutputStream ("/mnt/sdcard/sdcard/dcim/" + name);
SYSTEM.OUT.PRINTLN (name);
Fileout.write (data,0,data.length);
Fileout.flush ();
Fileout.close ();
catch (IOException e) {//Todo:handle exception System.out.println (e);}}
}; Class Preview extends Surfaceview implements Surfaceholder.callback {Preview (context) {super (context); mholder=
Getholder ();
Mholder.addcallback (this);
Mholder.settype (surfaceholder.surface_type_push_buffers); } public void SuRfacecreated (Surfaceholder holder) {mcamera=camera.open (); try {mcamera.setpreviewdisplay (holder);} catch (
IOException exception) {mcamera.release (); mcamera=null;}} public void surfacedestroyed (Surfaceholder holder) {Mcamera.stoppreview (), Mcamera.release ();} @Override public void Su Rfacechanged (surfaceholder holder, int format, int w, int h) {//TODO auto-generated method stub camera.parameters Parame
Ters=mcamera.getparameters ();
Parameters.setpictureformat (Pixelformat.jpeg);
Parameters.setpreviewsize (1024, 1024);
Mcamera.setparameters (parameters);
Mcamera.setdisplayorientation (90);
Mcamera.startpreview ();

 }
}
}

For more information on Android-related content readers can view the site topics: "Android File Operation tips Summary", "Android programming development of the SD card operation Summary", "Android Development introduction and Advanced Course", "Android Resources Operating Skills summary", " Android View tips Summary and a summary of the use of Android controls

I hope this article will help you with the Android program.

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.