Android's encapsulation call to the directional sensor

Source: Internet
Author: User

Android Automatic Sensormanager is easy to use, but in some cases we want to encapsulate the functionality:

    • Using only individual sensor, the function is relatively single
    • The raw data returned by the sensor will be processed by the algorithm to use the
    • Multiple frequent calls to disable sensor data in the program

Because the project needs to call the phone's direction information on many pages, the sensor's direction sensor is simply encapsulated, the source code is as follows:

 PackageCom.weicheche.android.service;Importjava.util.ArrayList;Importcom.****. Android.bean.ApplicationContext;ImportAndroid.hardware.Sensor;Importandroid.hardware.SensorEvent;ImportAndroid.hardware.SensorEventListener;ImportAndroid.hardware.SensorManager;ImportAndroid.os.Handler;ImportAndroid.os.SystemClock;/*** * @ClassName: Orientationservice * @Description: TODO (Package The orientation sensor that comes with the Android SDK) *@authorXuyong [email protected] * @date July 14, 2014 morning 2:24:10*/ Public classOrientationserviceImplementsSensoreventlistener {/** For classes that want to listen for directional changes, you need to implement this interface for inheritance*/     Public Static Abstract Interfaceorientationlistener{ Public Abstract voidOnorientationchanged (floatorientatoin); }        protected FinalHandler Mhandler =NewHandler (); PrivateSensormanager Sensormanager; PrivateSensor Morientationsensor; Private floatmtargetdirection = 0; PrivateArraylist<orientationlistener> ListenerList =NewArraylist<orientationlistener>(); Private LongDelaymillis = 20;  PublicOrientationservice () {//TODO auto-generated Constructor stubinit (); }    /*** * @Title: Registerlistener * @Description: TODO (Registers the class that needs to listen for direction changes into Orientationservice, the sensor in the service automatically opens )      * @paramListener *@throws* @date July 14, 2014 Morning 2:29:26 * Xuyong*/     Public voidRegisterlistener (Orientationlistener listener) {Listenerlist.add (listener); if(1 = =listenerlist.size ()) {            //There's just a new listener. Open the direction sensor and start the update thread when you joinStartService ();  Mhandler.postdelayed (Mcompassviewupdater, Delaymillis); //Delaymillis milliseconds to perform a direction update        }    }        /*** @Title: Unregisterlistener * @Description: TODO (when the activity is pause or destroyed, the service is removed from the service and is automatically stopped as per the situation) Work to the sensor) *@paramListener *@throws* @date July 14, 2014 Morning 2:30:45 * Xuyong*/     Public voidUnregisterlistener (Orientationlistener listener) {if((Listenerlist.remove (listener)) && 0 = =listenerlist.size ()) {            //if listener is removed after successful removal, no listener monitoring direction changes, pause direction sensorStopService (); }    }        /*** @Title: Setdelaymillis * @Description: TODO (set update interval, not less than 10ms) *@paramDelaymillis *@throws* @date July 14, 2014 Morning 2:34:10 * Xuyong*/     Public voidSetdelaymillis (LongDelaymillis) {        if(delaymillis>10){             This. Delaymillis =Delaymillis; }    }        /*** @Title: Ondestory * @Description: TODO (remove all listening classes and stop the direction sensor) *@throws* @date July 14, 2014 Morning 2:34:46 * Xuyong*/     Public voidondestory () {listenerlist.clear ();    StopService (); }        /*** @Title: Init * @Description: TODO (Initialize direction sensor) *@throws* @date July 14, 2014 Morning 12:36:53 * Xuyong*/@SuppressWarnings ("Deprecation")    Private voidinit () {Sensormanager=(Sensormanager) applicationcontext.getinstance (). GetContext (). Getsystemservice (        Android.content.Context.SENSOR_SERVICE); Try{morientationsensor=sensormanager.getsensorlist (sensor.type_orientation). Get (0); } Catch(Exception e) {//Todo:handle ExceptionMorientationsensor =NULL; }            }        Private voidStopService () {if(Morientationsensor! =NULL&& Sensormanager! =NULL) {Sensormanager.unregisterlistener ( This); }    }        Private voidStartService () {if(Morientationsensor! =NULL&& Sensormanager! =NULL) {Sensormanager.registerlistener ( This, Morientationsensor, sensormanager.sensor_delay_game); }    }        /*** This is the update Compass rotation thread, handler flexible use, every delaymillis milliseconds detection direction change value (such a mechanism is not very good, there may be thread block)*/    protectedRunnable Mcompassviewupdater =NewRunnable () {@Override Public voidrun () {if(Listenerlist.size () > 0) {//when listening, pass it on, and note that the incoming order is reversed to ensure that the nearest layer responds first.                 LongStartTime =Systemclock.uptimemillis ();  for(inti = Listenerlist.size ()-1; i>=0; i--) {((Orientationlistener) listenerlist.get (i)). onorientationchanged (mtargetdirection); }                //due to thread blocking, it can lead to delays and time control to compensate                LongEndTime =Systemclock.uptimemillis (); LongDelaytime = EndTime-StartTime; Delaytime= (Delaytime > Delaymillis)? 2: (delaymillis-delaytime);    Mhandler.postdelayed (Mcompassviewupdater, delaytime); //Better than a timer.            }                    }    }; /** No use currently*/@Override Public voidOnaccuracychanged (Sensor arg0,intarg1) {        //TODO auto-generated Method Stub    }        /*** @Title: onsensorchanged * @Description: TODO (directly call the SDK's own API to get direction information and later need to be modified to calculate the direction of the acceleration and geomagnetic data) *@paramEvent *@throws* @date July 11, 2014 PM 4:52:36 * Xuyong*/@SuppressWarnings ("Deprecation") @Override Public voidonsensorchanged (Sensorevent event) {//TODO auto-generated Method Stub        Switch(Event.sensor.getType ()) {//Note: The change method has been discouraged, consider modifying the direction value in the data acquisition direction here         Casesensor.type_orientation:floatDirection = event.values[sensormanager.data_x] * -1.0f; Mtargetdirection= (direction + 720)% 360;//assign to global variables, let the compass rotate             Break; default:             Break; }    }}

Call Method:

For any activity, inheritance implementation Orientationlistener, in Onresume and OnPause respectively register and note the PIN listener, the code is as follows:

1  Public classXxxxactivityImplementsOrientationlistener {2 3 @Override4     protected voidOnPause () {5        Super. OnPause ();6Applicationcontext.getinstance (). Getorientationservice (). Unregisterlistener ( This);7     }89@OverrideTen      Public voidOnresume () { One         Super. Onresume (); AApplicationcontext.getinstance (). Getorientationservice (). Registerlistener ( This); -     } -  the @Override -      Public voidOnorientationchanged (floatorientatoin) { -         //TODO auto-generated Method Stub - adapter.setorientation (orientatoin); +     }  -}

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.