Android Candid Camera function realization (mobile phone closed still photographed) detailed and instance code _android

Source: Internet
Author: User
Tags stub

Android Candid Camera function/Phone shutdown can take photos

The effect is as follows:

In fact, the camera and the record to achieve the same way, are used to WindowManager to draw the principle of small desktop controls. Then I will not say more ...

First, we need a surfaceview:

<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android=
  "http://schemas.android.com/" Apk/res/android "
  android:id=" @+id/small_window_layout "
  android:layout_width=" 1dip "
  android:layout_ height= "1dip"
  >
  <framelayout
    android:id= "@+id/percent"
    android:layout_width= "Fill_" Parent "
    android:layout_height=" fill_parent "
    android:gravity=" center "
    />
</ Linearlayout>

Second, then the operation is to produce this small control:

Public Photowindowsmallview {
    super (context);
    WindowManager = (WindowManager) context.getsystemservice (context.window_service);
    Layoutinflater.from (context)-Inflate (r.layout.float_window_small, this);
    View view = Findviewbyid (r.id.small_window_layout);
    Viewwidth = View.getlayoutparams (). width;
    Viewheight = View.getlayoutparams (). Height;    Surfaceview Percentview = (surfaceview) Findviewbyid (r.id.percent);    Percentview.settext (Mywindowmanager.getusedpercentvalue (context));
  }



  /**
   * The parameters of the small suspension window will be passed in to update the position of the small suspension window.
   *
   * @param params small suspension window parameters *
  /public void SetParams (Windowmanager.layoutparams params) {
    Mparams = params;
  }

Third, the desktop control has, the following of course is to use WindowManager added to the desktop:

 /** * Create a small suspension window.
     The initial position is the right middle position of the screen.
     * * @param context must be the context of the application.
      * * public void Createsmallwindow {mcontext = context;
      WindowManager WindowManager = Getwindowmanager (context);
      int screenwidth = Windowmanager.getdefaultdisplay (). GetWidth ();
      int screenheight = Windowmanager.getdefaultdisplay (). GetHeight ();
        if (Smallwindow = = null) {Smallwindow = new Photowindowsmallview (context);
          if (Smallwindowparams = = null) {smallwindowparams = new layoutparams ();
          Smallwindowparams.type = Layoutparams.type_phone;
          Smallwindowparams.format = pixelformat.rgba_8888; Smallwindowparams.flags = Layoutparams.flag_not_touch_modal |
          layoutparams.flag_not_focusable; smallwindowparams.gravity = Gravity.left |
          Gravity.top;
          Smallwindowparams.width = Photowindowsmallview.viewwidth;
Smallwindowparams.height = Photowindowsmallview.viewheight;          Smallwindowparams.x = ScreenWidth;
        Smallwindowparams.y = SCREENHEIGHT/2;
        } smallwindow.setparams (Smallwindowparams);

        Windowmanager.addview (Smallwindow, smallwindowparams);

      Msurfaceview = (framelayout) Smallwindow.findviewbyid (r.id.percent);
     }/** * Removes the small suspension window from the screen.
     * * @param context must be the context of the application. */public void Removesmallwindow {if (Smallwindow!= null) {WindowManager Windowmanag
        ER = getwindowmanager (context);
        Windowmanager.removeview (Smallwindow);
      Smallwindow = null;

 }
    }

Four, this time we need to have the surfaceview, then, how to operate in the background? It's natural to think of service.

To perform the operation of a desktop control in a service:

 @Override public
  int Onstartcommand (Intent Intent, int flags, int startid) {
    Mywindowmanager = new MYPHOTOWINDOWM Anager ();
    CreateWindow ();
    Return Super.onstartcommand (Intent, flags, Startid);
  }

  @Override public
  void OnDestroy () {
    Super.ondestroy ();

  }

  private void CreateWindow () {
    //The current interface is the desktop, and there is no floating window to display, create a floating window.
    Mywindowmanager.removesmallwindow (Getapplicationcontext ());
    Mywindowmanager.createsmallwindow (Getapplicationcontext ());

  }

V. Bind service in activity and take photos

Private class Myserviceconn implements Serviceconnection {

    @Override public
    void onserviceconnected ( ComponentName name, IBinder service) {
      //TODO auto-generated method stub
      Binder = ( Photowindowservice.myservicebinder) service;
      if (isvedio) {
        binder.startcarema ();
      } else {
        binder.stopcarema ();

    }} @Override public
    void onservicedisconnected (componentname name) {
      //TODO auto-generated method stub
    }< c15/>}

Control the beginning and end of the Mywindowmanager in the service

 public class Myservicebinder extends Binder {public
    void Startcarema () {
      mywindowmanager.startcarema ();
    } Public

    void Stopcarema () {
      mywindowmanager.stopcarema ();
    }
  }

Open or terminate photo operation at Myphotowindowmanager

 public void Startcarema () {
    ITT = inittimetotakepic.getinstance (mcontext);
    Itt.initview (Msurfaceview);
    Itt.start ();
  }

  public void Stopcarema () {
    if (ITT!= null)
      Itt.releasecarema ();
  }

Viii. related processing of photographing in inittimetotakepic

Package Com.ddv.www.candidphotodemo;
Import Android.annotation.TargetApi;
Import android.app.Activity;
Import Android.content.Context;
Import android.content.Intent;
Import Android.content.pm.PackageManager;
Import Android.hardware.Camera;
Import Android.hardware.Camera.AutoFocusCallback;
Import Android.hardware.Camera.PictureCallback;
Import Android.os.Build;
Import Android.os.Handler;
Import Android.os.Message;

Import Android.widget.FrameLayout;
Import Java.io.File;

Import Java.io.FileOutputStream; /** * Set Timer photo function * * @author <p> * Create timed Photo task * Cameratype Camera * resolutionstring Resolution * Tvsaveloc ation Save Address * etextension Expand name * Camerastart, start shooting time * Cameranumber, shoot number * Camerastop take Zhang * * *
  Lass Inittimetotakepic {private static inittimetotakepic minstance;
  private static int cameratype = 1;
  Context Mcontext;
  Static Framelayout Msurfaceviewframe;
  private static Camera Mcamera;
  private static Camerapreview Mpreview; PRivate static String resolutionstring = "1920x1080";
  private static String SaveLocation = Apputils.getsdcardpath ();
  private static String Extension = "JPG";
  private static String Camerastart = "1";
  private static String Cameranumber = "1";
  private static String Camerastop = "10";
  private static int number = 0;
  private static Boolean clearvoice = false;

  Private Intent Intent;
  Private Inittimetotakepic {this.mcontext = context;
    Synchronized static Inittimetotakepic getinstance (context context) {minstance = null;

    Minstance = new Inittimetotakepic (context);
  return minstance;
  public void Initview (Framelayout surfaceviewframe) {msurfaceviewframe = Surfaceviewframe; /** * Start timed photo and upload function * * Handler Mhandler = new Handler () {@Override public void handlemessage (Message m
          SG) {switch (msg.what) {case 1:LOGUTILS.V ("Start taking photos");
          Initcarema ();
        BreakCase 2:if (Mcamera = = null) {Releasecarema ();
            Number = 0;
          Mhandler.removecallbacksandmessages (NULL); else {if (number < integer.valueof (camerastop)) {Mcamera.autofocus (New Autofocuscallback (
                  {@Override public void Onautofocus (Boolean success, Camera Camera) {
                  Capture pictures from camera logutils.v ("autofocus" + success);
                    try {mcamera.takepicture (null, NULL, mpicture);
                  Mhandler.sendemptymessagedelayed (1, integer.valueof (cameranumber) * 1000);
                    catch (Exception e) {Releasecarema ();
                  Mhandler.removecallbacksandmessages (NULL);
            }
                }
              });
              else {Releasecarema ();
              Number = 0;
            Mhandler.removecallbacksandmessages (NULL);
  }        } break;

  }
    }
  };
    public void Start () {mhandler.sendemptymessagedelayed (1, 1 * 1000); start the camera after//7s} private void Initcarema () {
    LOGUTILS.V ("Initcarema");
      if (Mcamera = = null) {LOGUTILS.V ("camera=null");
      Mcamera = Getcamerainstance ();
      Mpreview = new Camerapreview (Mcontext, Mcamera);
      Msurfaceviewframe.removeallviews ();
    Msurfaceviewframe.addview (Mpreview); } logutils.v (Mcamera = null?)
    ' Mcamera is null ': ' Mcamera is not null ');
    Mcamera.startpreview (); Mhandler.sendemptymessagedelayed (2, integer.valueof (camerastart) * 1000); 3s camera/** * Detection device exists camera hardware/private Boolean Checkcamerahardware (context context) {if (context.ge
    Tpackagemanager (). Hassystemfeature (Packagemanager.feature_camera)) {//exists return true;
    else {//does not exist return false; }/** * Opens a camera/@TargetApi (build.version_codes. JELLY_BEAN_MR1) PublicStatic Camera getcamerainstance () {Camera c = null;
      try {c = camera.open (Cameratype);
      C.setdisplayorientation (90);
      Camera.parameters mparameters = C.getparameters ();
      Shutter sound c.enableshuttersound (clearvoice);
      Can be used to get the currently supported photo size, then//list<size> ms = Mparameters.getsupportedpicturesizes (); Mparameters.setpicturesize (Ms.get (0). Width, ms.get (0). height);
      The default maximum picture takes the maximum sharpness of the photo string[] Xes = Resolutionstring.split ("x");
      Logutils.i ("ms.get (0) .width==>" +ms.get (0). width);
      Logutils.i ("ms.get (0) .height==>" +ms.get (0). height);
      Logutils.i ("integer.valueof (Xes[0]) ==>" +integer.valueof (xes[0));
      Logutils.i ("integer.valueof (xes[1]) ==>" +integer.valueof (xes[1)); Mparameters.setpicturesize (Integer.valueof (Xes[0]), integer.valueof (xes[1));
    The default maximum picture takes the maximum sharpness of the photo c.setparameters (mparameters);
    catch (Exception e) {logutils.v ("Open camera failure failed");
  return C; } privatePicturecallback mpicture = new Picturecallback () {@Override public void Onpicturetaken (byte[) data, Camera Camer
      A) {//Get JPEG picture, and save on SD card String path = SaveLocation;
      File DIRF = new file (path);
      if (!dirf.exists ()) {dirf.mkdirs (); File PictureFile = new file (path + "/" + system.currenttimemillis () + "." + extension);//extension try {F
        Ileoutputstream fos = new FileOutputStream (picturefile);
        Fos.write (data);

        Fos.close ();
        LOGUTILS.V ("Save diagram Success");
        number++;
        Intent = new Intent ();
        Intent.setaction ("Camerafragment.start");
        Intent.putextra ("number", number);
      Mcontext.sendbroadcast (Intent);
        catch (Exception e) {logutils.v ("Save picture Failed");
      E.printstacktrace ();
    } releasecarema ();

  }
  };
      public void Releasecarema () {if (Mcamera!= null) {Mcamera.stoppreview ();
      Mcamera.release ();
    Mcamera = null;

 }
  }
}

Demo Download Address: http://www.jb51.net/softs/519032.html

Thank you for reading, I hope to help you, thank you for your support for this site!

Related Article

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.