How Android realizes the Candid Camera feature (phone shutdown still takes photos) tutorial

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:

<?xmlversion= "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:

Publicphotowindowsmallview (Context context) {
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 parameter of the small suspension window is passed in to update the position of the small suspension window.
*
* @param params small suspension window parameters
*/
Publicvoidsetparams (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.
*/
Publicvoidcreatesmallwindow (Context context) {
Mcontext = context;
WindowManager WindowManager = Getwindowmanager (context);
Intscreenwidth = Windowmanager.getdefaultdisplay (). GetWidth ();
Intscreenheight = Windowmanager.getdefaultdisplay (). GetHeight ();
if (Smallwindow ==null) {
Smallwindow =newphotowindowsmallview (context);
if (Smallwindowparams ==null) {
Smallwindowparams =newlayoutparams ();
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);
}
}
/**
* Remove the small suspension window from the screen.
*
* @param context must be the context of the application.
*/
Publicvoidremovesmallwindow (Context context) {
if (Smallwindow!=null) {
WindowManager WindowManager = 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
 publicintonstartcommand (Intent intent,intflags,intstartid) {
div>    mywindowmanager =newmyphotowindowmanager ();
   createwindow ();
   returnsuper.onstartcommand (Intent, flags, Startid);
 
 
  @Override
 publicvoidonde Stroy () {
   super.ondestroy ();
 
 
 
 privatevoidcreatewindow () {
   //The current interface is the desktop and no suspension window is displayed, create a floating window.
   mywindowmanager.removesmallwindow (Getapplicationcontext ());
   mywindowmanager.createsmallwindow (Getapplicationcontext ());
 
 

V. Bind service in activity and take photos

privateclassmyserviceconnimplementsserviceconnection {
@Override
publicvoidonserviceconnected (componentname name, IBinder service) {
TODO auto-generated Method Stub
Binder = (photowindowservice.myservicebinder) service;
if (Isvedio) {
Binder.startcarema ();
}else{
Binder.stopcarema ();
}
}
@Override
publicvoidonservicedisconnected (componentname name) {
TODO auto-generated Method Stub
}
}

Control the beginning and end of the Mywindowmanager in the service

Publicclassmyservicebinderextendsbinder {
Publicvoidstartcarema () {
Mywindowmanager.startcarema ();
}
Publicvoidstopcarema () {
Mywindowmanager.stopcarema ();
}
}

Open or terminate photo operation at Myphotowindowmanager

Publicvoidstartcarema () {
ITT = Inittimetotakepic.getinstance (Mcontext);
Itt.initview (Msurfaceview);
Itt.start ();
}
Publicvoidstopcarema () {
if (ITT!=null)
Itt.releasecarema ();
}

Viii. related processing of photographing in inittimetotakepic

Packagecom.ddv.www.candidphotodemo;
Importandroid.annotation.TargetApi;
importandroid.app.Activity;
Importandroid.content.Context;
Importandroid.content.Intent;
Importandroid.content.pm.PackageManager;
Importandroid.hardware.Camera;
Importandroid.hardware.Camera.AutoFocusCallback;
Importandroid.hardware.Camera.PictureCallback;
Importandroid.os.Build;
Importandroid.os.Handler;
Importandroid.os.Message;
Importandroid.widget.FrameLayout;
Importjava.io.File;
Importjava.io.FileOutputStream;
/**
* Set the timing camera function
*
* @author <p>
* Create a timed photo task
* Cameratype Camera
* Resolutionstring Resolution
* Tvsavelocation Save Address
* Etextension Development Name
* Camerastart, start shooting time
* Cameranumber, shooting times
* Camerastop shot Count
*/
Publicclassinittimetotakepic {
Privatestaticinittimetotakepic minstance;
Privatestaticintcameratype = 1;
Context Mcontext;
Staticframelayout Msurfaceviewframe;
Privatestaticcamera Mcamera;
Privatestaticcamerapreview Mpreview;
Privatestaticstring resolutionstring = "1920x1080";
privatestaticstring SaveLocation = Apputils.getsdcardpath ();
privatestaticstring extension = "JPG";
Privatestaticstring Camerastart = "1";
Privatestaticstring Cameranumber = "1";
Privatestaticstring camerastop = "10";
Privatestaticintnumber = 0;
Privatestaticbooleanclearvoice =false;
Privateintent Intent;
Privateinittimetotakepic (Context context) {
This.mcontext = context;
}
Publicsynchronizedstaticinittimetotakepic getinstance (Context context) {
Minstance =null;
Minstance =newinittimetotakepic (context);
Returnminstance;
}
Publicvoidinitview (Framelayout surfaceviewframe) {
Msurfaceviewframe = Surfaceviewframe;
}
/**
* Start timed photo and upload function
*/
Handler Mhandler =newhandler () {
@Override
Publicvoidhandlemessage (Message msg) {
Switch (msg.what) {
CASE1:
LOGUTILS.V ("Start taking pictures");
Initcarema ();
Break
CASE2:
if (Mcamera ==null) {
Releasecarema ();
Number = 0;
Mhandler.removecallbacksandmessages (NULL);
}else{
if (number < integer.valueof (camerastop)) {
Mcamera.autofocus (Newautofocuscallback () {
@Override
Publicvoidonautofocus (booleansuccess, Camera Camera) {
Capturing 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
}
}
};
Publicvoidstart () {
Mhandler.sendemptymessagedelayed (1,1*1000); start the camera after//7s
}
Privatevoidinitcarema () {
LOGUTILS.V ("Initcarema");
if (Mcamera ==null) {
LOGUTILS.V ("Camera=null");
Mcamera = Getcamerainstance ();
Mpreview =newcamerapreview (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); Photos after//3s
}
/**
* Detect whether the device exists camera hardware
*/
Privatebooleancheckcamerahardware (Context context) {
if (Context.getpackagemanager (). Hassystemfeature (
Packagemanager.feature_camera)) {
Exist
Returntrue;
}else{
does not exist
Returnfalse;
}
}
/**
* Open a camera
*/
@TargetApi (build.version_codes. JELLY_BEAN_MR1)
Publicstaticcamera getcamerainstance () {
Camera c =null;
try{
c = Camera.open (Cameratype);
C.setdisplayorientation (90);
Camera.parameters mparameters = C.getparameters ();
Shutter Sound
C.enableshuttersound (Clearvoice);
You can use the picture size that you currently support, and then
List<size> ms = Mparameters.getsupportedpicturesizes ();
Mparameters.setpicturesize (Ms.get (0). Width, ms.get (0). height); Default maximum photo to take maximum clarity
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));//default maximum photo taking maximum resolution
C.setparameters (mparameters);
}catch (Exception e) {
LOGUTILS.V ("Open camera failure failed");
}
RETURNC;
}
Privatepicturecallback mpicture =newpicturecallback () {
@Override
Publicvoidonpicturetaken (byte[] data, Camera Camera) {
Get the JPEG picture and save it on the SD card
String path = SaveLocation;
File DIRF =newfile (path);
if (!dirf.exists ()) {
Dirf.mkdirs ();
}
File picturefile =newfile (path + "/" + system.currenttimemillis () + ".") + extension);//Extension
try{
FileOutputStream Fos =newfileoutputstream (picturefile);
Fos.write (data);
Fos.close ();
LOGUTILS.V ("Save diagram Success");
number++;
Intent =newintent ();
Intent.setaction ("Camerafragment.start");
Intent.putextra ("number", number);
Mcontext.sendbroadcast (Intent);
}catch (Exception e) {
LOGUTILS.V ("Save picture Failed");
E.printstacktrace ();
}
Releasecarema ();
}
};
Publicvoidreleasecarema () {
if (Mcamera!=null) {
Mcamera.stoppreview ();
Mcamera.release ();
Mcamera =null;
}
}
}
Original link: http://blog.csdn.net/huangxiaoguo1/article/details/53666047

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.