Float Camera Service

Source: Internet
Author: User

1. Mainactivity.java

Package Com.jean.lee.floatcamera;import Android.annotation.suppresslint;import Android.app.activity;import Android.content.intent;import Android.content.sharedpreferences;import Android.graphics.rect;import Android.hardware.camera;import Android.os.bundle;import Android.util.displaymetrics;import android.widget.Toast; Import Com.jean.lee.floatcamera.service.floatcameraservice;import com.jean.lee.floatcamera.util.seclog;@  Suppresslint ("Newapi") public class Mainactivity extends Activity {private static final String TAG = "Floatcamera";p rivate Static final String float_cam_service_preferences = "Pref_float_camera_service";p rivate static final string Key_ preferences_service_started = "key_preferences_service_started";p rivate static final String Key_preferences_screen_ HEIGHT = "Key_preferences_screen_height";p rivate static final String key_preferences_camera_numbers = "key_preferences _camera_numbers "; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); SECLOG.E (TAG, "onCreate");} @Overrideprotected void Onresume () {SECLOG.E (TAG, "Onresume"); Sharedpreferences msharedpreferences = getsharedpreferences (float_cam_service_preferences, Activity.MODE_PRIVATE); if (Msharedpreferences.getint (Key_preferences_camera_numbers,-2) = = 0) {Toast.maketext (this, r.string.toast_no_ Camera, Toast.length_short). Show (); Finish ();} else if (Msharedpreferences.getint (Key_preferences_camera_numbers,-2) = =-2) {Sharedpreferences.editor Editor =        Msharedpreferences.edit ();        Editor.putint (Key_preferences_camera_numbers, Camera.getnumberofcameras ()); Editor.commit ();}        if (Msharedpreferences.getint (key_preferences_screen_height, 0) = = 0) {displaymetrics dm = new Displaymetrics ();        This.getwindowmanager (). Getdefaultdisplay (). Getmetrics (DM);        int screenheight = Dm.heightpixels;        SECLOG.E (TAG, "screenheight=" +screenheight);        Sharedpreferences.editor Editor = Msharedpreferences.edit (); Editor.Putint (Key_preferences_screen_height, screenheight);        Editor.commit ();} Intent Intent = new Intent (mainactivity.this, Floatcameraservice.class); Sharedpreferences.editor Editor = Msharedpreferences.edit (); if (!msharedpreferences.getboolean (KEY_PREFERENCES_ Service_started, False)) {SECLOG.E (TAG, "Call Start Service"); StartService (intent); Editor.putboolean (Key_ Preferences_service_started, True);} else {SECLOG.E (TAG, "Call Stop Service"); StopService (intent); Editor.putboolean (key_preferences_service_started, FALSE);} Editor.commit (); Finish (); Super.onresume ();} @Overrideprotected void OnDestroy () {SECLOG.E (TAG, "OnDestroy"); Super.ondestroy ();} @Overrideprotected void OnPause () {SECLOG.E (TAG, "OnPause"); Super.onpause ();}}


2. Floatcameraservice.java

Package Com.jean.lee.floatcamera.service;import Java.io.ioexception;import Java.lang.reflect.field;import Android.annotation.suppresslint;import Android.app.activity;import Android.app.service;import Android.content.context;import Android.content.intent;import Android.content.sharedpreferences;import Android.graphics.pixelformat;import Android.hardware.camera;import Android.hardware.camera.camerainfo;import Android.hardware.camera.parameters;import Android.os.ibinder;import Android.os.vibrator;import Android.view.gravity;import Android.view.layoutinflater;import Android.view.motionevent;import Android.view.surfaceholder;import Android.view.surfaceview;import Android.view.view;import Android.view.view.onlongclicklistener;import Android.view.view.ontouchlistener;import Android.view.WindowManager ; import Android.view.windowmanager.layoutparams;import Android.widget.linearlayout;import android.widget.Toast; Import Com.jean.lee.floatcamera.r;import Com.jean.lee.floatcamera.util.SecLog; @SuppreSslint ("Newapi") public class Floatcameraservice extends Service implements surfaceholder.callback{private static final String TAG = "Floatcameraservice";p rivate static final String float_cam_service_preferences = "Pref_float_camera_ Service ";p rivate static final String key_preferences_camera_id =" key_preferences_camera_id ";p rivate static final String key_preferences_window_x = "key_preferences_window_x";p rivate static final String key_preferences_window_y = " Key_preferences_window_y ";p rivate static final String key_preferences_window_width_back =" Key_preferences_window_ Width_back ";p rivate static final String key_preferences_window_height_back =" Key_preferences_window_height_back "; private static final String Key_preferences_window_width_front = "Key_preferences_window_width_front";p rivate static Final string key_preferences_window_height_front = "Key_preferences_window_height_front";p rivate static final string Key_preferences_statusbar_height = "Key_preferences_statusbar_height";p RivaTe static final String key_preferences_screen_height = "Key_preferences_screen_height";p rivate static final string Key_ Preferences_camera_numbers = "Key_preferences_camera_numbers"; LinearLayout mfloatlayout; Windowmanager.layoutparams Wmparams; WindowManager mwindowmanager;private surfaceview msvpreview;private surfaceholder mSurfaceHolder;private Camera Mcamera;private Parameters mparameters;private static final int default_camera_id = Camerainfo.camera_facing_back; private static int mcameraid = default_camera_id;private static int mcameranumbers;private sharedpreferences Msharedpreferences;private Boolean blongpressed = false;private Boolean bmultitouchpressed = false;private static int mSt Atusbarheight = 0;private static int mwindowwidth = 270;private static int mwindowheight = 480;private static final int PR Eview_4_3_width = 300;private static final int preview_4_3_height = 400;private static final int preview_16_9_width = 270; private static final int preview_16_9_height = 480; @Overridepublic void OnCreate () {SECLOG.E (TAG, "onCreate"); Super.oncreate ();} @Overridepublic void OnDestroy () {SECLOG.E (TAG, "OnDestroy"); if (mfloatlayout! = null) {Mwindowmanag        Er.removeview (mfloatlayout); }if (null! = Mcamera) {Mcamera.stoppreview (); Mcamera.release (); mcamera = null;} Super.ondestroy ();} @Overridepublic int Onstartcommand (Intent Intent, int flags, int startid) {seclog.e (TAG, "Onstartcommand"); Msharedpreferences = Getsharedpreferences (float_cam_service_preferences, activity.mode_private);        Layoutinflater inflater = Layoutinflater.from (Getapplication ());        Mfloatlayout = (linearlayout) inflater.inflate (r.layout.float_layout, NULL);        Msvpreview = (Surfaceview) Mfloatlayout.findviewbyid (R.id.sv_preview);        Msurfaceholder = Msvpreview.getholder ();        Msurfaceholder.addcallback (this);        Mstatusbarheight = Msharedpreferences.getint (key_preferences_statusbar_height, 0); if (0 = = mstatusbarheight) {mstatusbarheight = GetstatUsbarheight (Getbasecontext ()); Sharedpreferences.editor Editor = Msharedpreferences.edit (); Editor.putint (Key_preferences_statusbar_height,        Mstatusbarheight); Editor.commit (); } opencamera (); Createfloatview (); return Super.onstartcommand (Intent, flags, Startid);} @Overridepublic boolean onunbind (Intent Intent) {seclog.e (TAG, "Onunbind"); return Super.onunbind (Intent);} @Overridepublic ibinder onbind (Intent arg0) {seclog.e (TAG, "Onbind"); return null;}        @SuppressLint ("Inflateparams") private void Createfloatview () {SECLOG.E (TAG, "Createfloatview");          Wmparams = new Windowmanager.layoutparams (); Mwindowmanager = (WindowManager) getapplication (). Getsystemservice (Getapplication ().          Window_service);           Wmparams.type = Layoutparams.type_phone;        Set the picture format, the effect is transparent Wmparams.format = pixelformat.rgba_8888;                Set the floating window not to be focusable (operation that enables operation of other visible windows except floating windows) Wmparams.flags = layoutparams.flag_not_focusable;       Adjust the hover window to display the docked position to the left top   wmparams.gravity = Gravity.left |                 Gravity.top;        In the upper left corner of the screen as the origin, set X, y initial value, relative to gravity wmparams.x = Msharedpreferences.getint (key_preferences_window_x, 0);         Wmparams.y = Msharedpreferences.getint (key_preferences_window_y, 0);          /*//Set the hover window length-width data wmparams.width = WindowManager.LayoutParams.WRAP_CONTENT;         Wmparams.height = windowmanager.layoutparams.wrap_content;*/setoptimizewindowsize ();        Set the hover window length-width data wmparams.width = mwindowwidth;                Wmparams.height = Mwindowheight;        Mwindowmanager.addview (Mfloatlayout, wmparams);                Mfloatlayout.measure (View.MeasureSpec.makeMeasureSpec (0, View.MeasureSpec.UNSPECIFIED), View.measurespec                  . Makemeasurespec (0, View.MeasureSpec.UNSPECIFIED)); Mfloatlayout.setontouchlistener (New Ontouchlistener () {@Overridepublic Boolean OnTouch (View arg0, motionevent event) { Switch (event.getactionmasked ()) {case Motionevent.actioN_DOWN:SECLOG.E (Tag, "OnTouch, Action_down"); break;case motionevent.action_move:seclog.e (Tag, "OnTouch, Action_move if (blongpressed) {//GETRAWX is the coordinate of the touch position relative to the screen, the getx is relative to the button's coordinates wmparams.x = (int) event.getrawx ()-Msvpreview.getmeasu          Redwidth ()/2;        Minus 25 is the height of the status bar WMPARAMS.Y = (int) Event.getrawy ()-msvpreview.getmeasuredheight ()/2-mstatusbarheight; Mwindowmanager.updateviewlayout (Mfloatlayout, wmparams);} Break;case motionevent.action_pointer_down:seclog.e (TAG, "OnTouch, Action_pointer_down"); break;case MOTIONEVENT.ACTION_POINTER_UP:SECLOG.E (TAG, "OnTouch, action_pointer_up"); Break;case motionevent.action_up: SECLOG.E (TAG, "OnTouch, action_up"); if (blongpressed) {blongpressed = false; Sharedpreferences.editor Editor = Msharedpreferences.edit (); Editor.putint (key_preferences_window_x, wmParams.x); Editor.putint (key_preferences_window_y, Wmparams.y); Editor.commit ();} Else{if (Msharedpreferences.getint (Key_preferences_camera_numbers,-2) = = 1) {Toast.maketext (GetBaseContExt (), R.string.toast_only_one_camera, Toast.length_short). Show (); return false;} Switchcamera (); Startpreview ();} BREAK;DEFAULT:SECLOG.E (TAG, "ontouch,event=" +event.getactionmasked ());                return false;}                }); Mfloatlayout.setonlongclicklistener (New Onlongclicklistener () {@Overridepublic Boolean onlongclick (View arg0) { SECLOG.E (TAG, "Onlongclick"); blongpressed = true;                Vibrator Vibrator = (Vibrator) getsystemservice (Context.vibrator_service); vibrator.vibrate (+); return false;}     }); } @Overridepublic void Surfacechanged (Surfaceholder arg0, int arg1, int arg2, int arg3) {seclog.e (TAG, "surfacechanged");} @Overridepublic void surfacecreated (Surfaceholder arg0) {seclog.e (TAG, "surfacecreated"); Startpreview ();} private void Opencamera () {SECLOG.E (TAG, "Opencamera"); if (null = = Mcamera && null! = msharedpreferences) { Mcameraid = Msharedpreferences.getint (key_preferences_camera_id, default_camera_id); MCamera = Camera.open (mCameraId ); mparameters = MCAmera.getparameters ();}} private void Switchcamera () {SECLOG.E (TAG, "Switchcamera"); if (null! = Mcamera) {Mcamera.stoppreview (); mcamera.release (); mcamera = null;} Sharedpreferences.editor Editor = Msharedpreferences.edit (); mcameraid = Msharedpreferences.getint (KEY_PREFERENCES_ camera_id, default_camera_id); if (camerainfo.camera_facing_back = = mcameraid) {Mcameraid = Camerainfo.camera_facing_ Front;mcamera = Camera.open (Mcameraid);} Else{mcameraid = Camerainfo.camera_facing_back;mcamera = Camera.open (Mcameraid);} Editor.putint (key_preferences_camera_id, Mcameraid); Editor.commit (); if (Mcamera! = null) {mparameters = Mcamera.getparameters ();}} private void Startpreview () {SECLOG.E (TAG, "Startpreview"), if (null! = Mcamera) {try {mcamera.setpreviewdisplay ( Msurfaceholder);} catch (IOException e) {e.printstacktrace ();} if (null! = mparameters) {seclog.e (TAG, "Preview Size:" +mparameters.getpreviewsize (). width+ "X" + Mparameters.getpreviewsize (). height);} Mcamera.setdisplayorientation (+); Mcamera.startpreview (); updateWindownsize ();}} @Overridepublic void surfacedestroyed (Surfaceholder arg0) {seclog.e (TAG, "surfacedestroyed");}        public static int Getstatusbarheight (context context) {SECLOG.E (TAG, "getstatusbarheight");        Class<?> c = null;        Object obj = null;        Field field = NULL;        int x = 0, statusbarheight = 0;            try {c = class.forname ("Com.android.internal.r$dimen");            obj = C.newinstance ();            field = C.getfield ("Status_bar_height");            x = Integer.parseint (Field.get (obj). toString ());        Statusbarheight = Context.getresources (). getdimensionpixelsize (x);        } catch (Exception E1) {e1.printstacktrace ();    } return statusbarheight; }public void Setoptimizewindowsize () {SECLOG.E (TAG, "setoptimizewindowsize"); if (Mcameraid = = Camerainfo.camera_ Facing_back) {mwindowwidth = Msharedpreferences.getint (key_preferences_window_width_back, 0); mWindowHeight = Msharedpreferences.getint (Key_preferences_window_Height_back, 0);} Else{mwindowwidth = Msharedpreferences.getint (key_preferences_window_width_front, 0); mWindowHeight = Msharedpreferences.getint (Key_preferences_window_height_front, 0);} if (0 = = Mwindowwidth | | 0 = = mwindowheight) {int screenheight = Msharedpreferences.getint (Key_preferences_screen_height, 0) Float ratio = (float) mparameters.getpreviewsize (). width/(float) mparameters.getpreviewsize (). Height;if (Math.Abs (ratio-16.0/9.0) < 1.0E-6) {//16/9mwindowwidth = Preview_16_9_width;mwindowheight = Preview_16_9_height;if ( ScreenHeight < +) {mwindowwidth = Mwindowwidth*5/6;mwindowheight = MWINDOWHEIGHT*5/6;}} else if (Math.Abs (ratio-4.0/3.0) < 1.0E-6) {mwindowwidth = Preview_4_3_width;mwindowheight = Preview_4_3_height;if ( ScreenHeight < +) {mwindowwidth = Mwindowwidth*4/5;mwindowheight = MWINDOWHEIGHT*4/5;}} Else{mwindowwidth = Preview_4_3_width;mwindowheight = Preview_4_3_height;} SECLOG.E (TAG, "width height:" +mwindowwidth+ "," +mwindowheight); Sharedpreferences.editor Editor =Msharedpreferences.edit (); if (Mcameraid = = Camerainfo.camera_facing_back) {editor.putint (key_preferences_window_ Width_back, Mwindowwidth); Editor.putint (Key_preferences_window_height_back, mwindowheight);} Else{editor.putint (Key_preferences_window_width_front, mwindowwidth); Editor.putint (KEY_PREFERENCES_WINDOW_ Height_front, mwindowheight);} Editor.commit ();}} public void Updatewindownsize () {SECLOG.E (TAG, "updatewindownsize"); Setoptimizewindowsize (); wmparams.width =        Mwindowwidth;                Wmparams.height = Mwindowheight; Mwindowmanager.updateviewlayout (Mfloatlayout, Wmparams);}}


3. Manifest.xml

<?xml version= "1.0" encoding= "Utf-8"? ><manifest xmlns:android= "http://schemas.android.com/apk/res/ Android "package=" Com.jean.lee.floatcamera "android:versioncode=" 1 "android:versionname=" 1.0 "> &LT;USES-SD K android:minsdkversion= "8" android:targetsdkversion= "/> <uses-permission android:name=" and Roid.permission.SYSTEM_ALERT_WINDOW "/> <uses-permission android:name=" Android.permission.CAMERA "/> <        Uses-permission android:name= "Android.permission.VIBRATE"/> <application android:allowbackup= "true" android:icon= "@drawable/ic_launcher" android:label= "@string/app_name" > <activity Android : Name= ".            Mainactivity "android:label=" @string/app_name "Android:theme=" @android: Style/theme.nodisplay "> <intent-filter> <action android:name= "Android.intent.action.MAIN"/> & Lt;category android:name= "Android.Intent.category.LAUNCHER "/> </intent-filter> </activity> <service android:name = ". Service. Floatcameraservice "></service> </application></manifest>


4. Float_layout.xml

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "    android:layout_width=" match_parent "    android:layout_height=" match_parent "    android:o rientation= "vertical" >        <surfaceview    android:id= "@+id/sv_preview"    android:visibility= "visible "    android:text=" testtest "        android:layout_width=" match_parent "        android:layout_height=" Match_parent " /></linearlayout>


Float Camera Service

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.