Distance sensor implementation lock tutorial + source code

Source: Internet
Author: User
First, let's talk about Android Under the Platform 11 Sensor Type: 1. Accelerometer Acceleration: Describes acceleration. 2. Gravity Gravity, which we all know. 3. Gyroscope Gyroscope, which is more powerful for object drop detection. It will be a little pity if the development game is less, API level 9 New type. 4. Light Light sensors, many Android The screen brightness of the mobile phone is automatically adjusted according to the sensor array. 5. linear_acceleration Linear Accelerator, API level 9 Added. 6. magnetic_field Pole sensor. 7. Orientation Direction sensor. 8. Pressure Pressure Sensor. 9. Proximity The distance sensor is useful for turning off the screen backlight after a call. 10. rotation_vector Rotation Vector, For Android 2.3 Newly Added: If we process images in the past, we will find this useful, but it is still useful for game development. 11. Temperature The temperature sensor can obtain the internal temperature of the mobile phone, but there is a gap with the surrounding area. After all, the internal temperature of the mobile phone is usually relatively high. To be good at applying these resources, we need to talk about distance sensors today. The principle of this lock frequency is also very simple, that is, when an object is near the distance sensor, it will trigger the event, and then apply for the power lock of the device in the event, let the screen in a black screen, then, when the object leaves the sensor and releases the power lock of the device OK . Next let's take a look Code The mainactivity. Java class is very simple, that is, to start a service.
Public class mainactivity extends activity {/** called when the activity is first created. * // @ overridepublic void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); intent = new intent (mainactivity. this, myservice. class); startservice (intent );}}

Then the main content of myservice. Java

Public class myservice extends Service {private sensormanager mmanager; private sensor msensor = NULL; private sensoreventlistener mlistener = NULL; private powermanager localpowermanager = NULL; private powermanager. wakelock localwakelock = NULL; @ overridepublic void oncreate () {// gets the system service power_service, and returns a powermanager object localpowermanager = (powermanager) getsystemservice (context. power_service); // obtain powerm Anager. wakelock object, followed by the parameter | indicates that two values are passed in at the same time, and finally the tag localwakelock = This used in logcat. localpowermanager. newwakelock (32, "mypower"); // gets the system service sensor_service, and returns a sensormanager object mmanager = (sensormanager) getsystemservice (context. sensor_service); // obtain the Sensor Object msensor = mmanager. getdefasensensor (sensor. type_proximity); // register sensor event mlistener = new sensoreventlistener () {@ overridepublic void onsensorchanged (sensorevent event) {Float [] its = event. Values; If (its! = NULL & event. sensor. getType () = sensor. type_proximity) {system. out. println ("its [0]:" + its [0]); // after testing, the value of its [0] returned when the close sensor is attached to the hand is 0.0, returns 1.0if (its [0] = 0.0) when the hand leaves {// close to the mobile phone system. out. println ("put your hands on... "); If (localwakelock. isheld () {return;} elselocalwakelock. acquire (); // apply for a device power lock} else {// stay away from the mobile phone system. out. println ("hands off... "); If (localwakelock. isheld () {return;} elselocalwakelock. setreferencecounted (false); localwakelock. release (); // release device power lock }}@ overridepublic void onaccuracychanged (sensor, int accuracy) {}}}@ overridepublic int onstartcommand (intent, int flags, int startid) {// register the listener mmanager. registerlistener (mlistener, msensor, sensormanager. sensor_delay_game); return Super. onstartcommand (intent, flags, startid) ;}@ overridepublic void ondestroy () {// cancel listening to mmanager. unregisterlistener (mlistener); super. ondestroy () ;}@ overridepublic ibinder onbind (intent) {return NULL ;}}

Androidmanifest. xmlTo add permissions < Uses-Permission Android: Name = "Android. Permission. device_power" /> <Uses-Permission Android: Name = "Android. Permission. wake_lock" />

 

For time reasons, I only implemented the function here, and there are still a lot to be optimized. If you need it, you can add it yourself. Optimization 1: When you press it, the screen will be locked, but the sensor event will still be triggered. That is to say, when you block the distance sensor and then open it, the screen will still be on. Solution: when the system lockscreen or black screen broadcasts two messages:Action_screen_offAndAction_screen_onSo we can write a broadcastreceiver to accept the broadcast and handle it accordingly. You can stop the service when the screen is black, and then start the service after the screen is on. Or define a Boolean variable. If the black screen is false and the light is true, the variable is determined to be true. You can apply for a power lock. The approximate code is as follows:
 
Public class myincluer extends broadcastreceiver {@ overridepublic void onreceive (context, intent) {string action = intent. getaction (); If (action. equals ("android. intent. action. screen_off ") {} else if (action. equals ("android. intent. action. screen_on ")){}}}

Optimization 2: You can manually close and start the service. You can add checkpoints in mainactivity to enable and stop services. This should be simple and not detailed.

 

Optimization 3: Automatic startup. This is not enough. There is a lot of information on the Internet.

I will explain it later. Powermanager class. The powermanager class is mainly used to control the power status. The API provided by this class can be used to control the battery standby time, which is generally not used. If you do need to use it, try to use the lowest level of wakelocks lock. And make sure to release it after use. You can use context. getsystemservice (context. power_service) to obtain the powermanager instance. The main newwakelock method in powermanager. the SDK source code is as follows:
/*** Get a wake lock at the level of the flags parameter. call * {@ link wakelock # acquire ()} on the object to acquire the * wake lock, and {@ link wakelock # release ()} When you are done. ** {@ samplecode * powermanager PM = (powermanager) mcontext. getsystemservice (* context. power_service); * powermanager. wakelock WL = PM. newwakelock (* powermanager. screen_dim_wake_lock * | powermanager. on_after_release, * tag); * WL. acquire ();*//... * WL. release (); *} ** @ Param flags combination of flag values defining the requested behavior of the wakelock. * @ Param tag your class name (or other tag) for debugging purposes. ** @ see wakelock # acquire () * @ see wakelock # release () */Public wakelock newwakelock (INT flags, string tag) {return New wakelock (flags, tag );}

This method will create a wakelock object. by calling this object method, you can easily control the power status. The method is as follows:

Powermanager PM = (powermanager) getsystemservice (context. power_service); powermanager. wakelock WL = PM. newwakelock (powermanager. screen_dim_wake_lock, "my tag"); WL. acquire (); the screen will stay in the set state, usually bright, dark state WL. release (); release the running CPU or close the screen.

Flags parameter description: * CPU Screen Keyboard
* Partial_wake_lock on off
* Screen_dim_wake_lock on dim off
* Screen_bright_wake_lock on bright off
* Full_wake_lock on bright

 

If you hold the partial_wake_lock lock, the CPU continues to run no matter whether the timer or even press the power button. Unless you release it. Other locks, although the CPU is also running, when you press the power button, the device will immediately enter the sleep state.

Here, there is nothing to do with it. The source code will be attached below. (ThisProgramTest on the HTC G7 real machine only ). Http://files.cnblogs.com/feifei1010/Keylock.rar You are welcome to join the group to make progress with those who love Android development.Nanjing group 220818530,Chengdu group, 252743807,Xi'an group 252746034,Wuhan group 121592153,Hangzhou group 253603803,Xiamen group 253604146

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.