Copyright notice: This article from Springer's blog, reproduced please be sure to indicate the source.
I. Overview of WakeLock
Wakelock is a mechanism of locking, as long as there is an application holding this lock, the CPU will not enter the dormant state, has been in a working state. For example, the phone screen when the screen is closed, some applications can still wake up the screen prompts the user message, here is the use of the Wakelock lock mechanism, although the phone screen is closed, but these applications are still running. The problem with the phone's power consumption is that most developers do not use the lock properly and become a "standby killer".
Android phones have two processors, one called Application Processor (AP), one called Baseband Processor (BP). The AP is an arm-architected processor for running the linux+android system, and BP is used to run a real-time operating system (RTOS), and the communication stack runs on the BP RTOS. Non-talk time, BP's energy consumption is basically around 5mA, and the AP as long as the non-dormant state, energy consumption at least 50mA, the implementation of graphics operations will be higher. In addition, the LCD operating power consumption around 100mA, WiFi is also around 100mA. When the phone is in standby, the AP, LCD, WiFi all go into hibernation, and the code of the app in Android will stop executing.
In order to ensure the proper execution of critical code in the application, Android provides the API for Wake Lock, which allows the application to have permission to prevent the AP from entering hibernation through code. However, if you do not understand the intentions of the Android designer to misuse the wake Lock API, in order to its own program in the background of the normal operation and long time to prevent the AP into hibernation, will become a standby battery killer.
So what's the wake Lock API for? Heartbeat packet from request to answer, wire break re-login and other key logic of the execution process, you need wake lock to protect. Once a key logical execution succeeds, the Wake Lock should be released immediately. Two heartbeat request interval of 5-10 minutes, basic not how to consume electricity.
Second,the use of WakeLock
Get the Wakelock instance code as follows:
PowerManager pm = (powermanager) getsystemservice (context.power_service); WakeLock WakeLock = Pm.newwakelock (Powermanager.partial_wake_lock, "Mywakelocktag");
The Powermanager.partiial_wake_lock in newwakelock (int levelandflags, String tag) is a flag bit, which is used to control the type of the acquired Wakelock object. The main control of the CPU work when the screen needs to be lit and the keyboard light needs to be lit, the flag is described as follows:
Levelandflags |
Whether the CPU is running |
Is the screen lit? |
is the keypad light on? |
Partial_wake_lock |
Is |
Whether |
Whether |
Screen_dim_wake_lock |
Is |
Low brightness |
Whether |
Screen_bright_wake_lock |
Is |
High brightness |
Whether |
Full_wake_lock |
Is |
Is |
Is |
Special Note : Starting with API level 17, Full_wake_lock will be deprecated. Apps should use flag_keep_screen_on.
The WakeLock class can be used to control the operating state of the device. Using acquire in this class can keep the CPU in a working state and call release to shut down if you do not need to make the CPU work.
(1), Auto release
If we call acquire (long timeout) then we do not need to manually call release () to release the lock, the system will help us release after timeout time.
(2), manual release
If we call acquire () then we need to manually call Release () to release the lock.
Finally, use the WakeLock class to remember to add the following permissions:
1 <uses-permission android:name= "Android.permission.WAKE_LOCK"/>
Note: When using this class, you must ensure that acquire and release are paired.
Three, keep the screen solid
The best way to do this is to use flag_keep_screen_on 's FLAG in the activity.
1 Public classMainactivityextendsActivity {2 @Override3 protected voidonCreate (Bundle savedinstancestate) {4 Super. OnCreate (savedinstancestate);5 Setcontentview (r.layout.activity_main);6 GetWindow (). Addflags (WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);7 }8}
The benefit of this approach is that it is not like a wake-up lock (wake locks) and requires some specific permissions (permission). and can correctly manage the switch between different apps, without worrying about the release of useless resources.
Another way is to use the Android:keepscreenon property in the layout file:
1 <relativelayout xmlns:android= "Http://schemas.android.com/apk/res/android"23 android:layout_width= "Match_parent"4 android:layout_height= "Match_parent"5 Android:keepscreenon= "true" >6 ... 7 </RelativeLayout>
Android:keepscreenon = "true" has the same effect as flag_keep_screen_on. The advantage of using code is that you allow you to turn off the screen where you need it.
Note : Generally do not need to remove flag_keep_screen_on Flag,windowmanager will manage the program into the background back to the operation of the foreground. If you do need to clear the solid FLAG manually, use GetWindow (). Clearflags (WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
iv. Examples ofwakefulbroadcastreceiver + intentservice
Intentserviceuse please refer to my previous blog: Android Intentservice Usage Introduction and source code parsing
Wakefulbroadcastreceiver is a special case of broadcastreceiver. It will create and manage a partial_wake_lock type of Wakelock for your app. Wakefulbroadcastreceiver the work to the service (usually Intentservice) and ensures that the device does not go into hibernation during the handover. If you do not hold wakelock, it is easy for the device to hibernate before the task is done. The end result is that your app doesn't know when it will be able to get the job done, believing it's not what you want.
Use the Startwakefulservice () method to start the service, compared to StartService () , when the service is started, and the wake-up lock is enabled.
When the background service task is complete, call wlwakefulreceiver.completewakefulintent () to release the wake-up lock.
The Wlwakefulreceiver class is as follows:
1 Public classWlwakefulreceiverextendsWakefulbroadcastreceiver {2 3 Private Static FinalString TAG = "MyTag";4 5 @Override6 Public voidOnReceive (Context context, Intent Intent) {7 //8String extra = Intent.getstringextra ("MSG");9LOG.I (TAG, "onreceive:" +extra);TenIntent serviceintent =NewIntent (context, Myintentservice.class); OneServiceintent.putextra ("MSG", extra); A Startwakefulservice (context, serviceintent); - } -}
It's easy to print the information and call the Startwakefulservice method to start the service.
The Myintentservice class is as follows:
1 Public classMyintentserviceextendsIntentservice {2 3 Private Static FinalString TAG = "MyTag";4 5 PublicMyintentservice () {6 Super("Myintentservice");7 }8 9 @OverrideTen protected voidonhandleintent (Intent Intent) { One //executes in a child thread ALOG.I (TAG, "Onhandleintent"); - for(inti = 0; I < 10; i++) { - Try { theThread.Sleep (3000); -String extra = Intent.getstringextra ("MSG"); -LOG.I (TAG, "onhandleintent:" +extra); -}Catch(interruptedexception e) { + e.printstacktrace (); - } + } A //call Completewakefulintent to release the wake-up lock. at wlwakefulreceiver.completewakefulintent (intent); - } -}
It is also simple and time consuming to print information, but after executing your business logic, remember to call Completewakefulintent to release the wake-up lock.
The end is to start the broadcast receiver and join the permissions and statements:
New Intent ("Wang_lei"); Intent.putextra ("msg", "Learning wake_lock ... "); Sendbroadcast (intent); <uses-permission android:name= "Android.permission.WAKE_LOCK"/><receiver android:name= ". Wlwakefulreceiver "> <intent-filter> <action android:name=" Wang_lei "/> </ Intent-filter></receiver><service android:name= ". Myintentservice "></service>
Well, write a program run found in time press the Power key screen close still have log print out.
To this end, Wakelock lock is mainly relative to the system of sleep, meaning that my program to the CPU added this lock the system will not hibernate, the purpose is to fully cooperate with the operation of our program. In some cases, if you do not do so, there will be some problems, such as the timely communication of the heartbeat pack will be put off the screen shortly after the network access and other issues. So inside there is a lot of use to the Wake_lock lock. hope that through the above-mentioned joint learning you can use Wakelock correctly, do not do battery killer.
Comprehensive analysis of Wakelock lock mechanism for Android power optimization