1. apply the wake lock tool class AlertWakeLock
After the mobile phone is dormant, the application's calculation, timing and download may be dormant due to the CPU, resulting in the application itself unable to receive the message, data and broadcast in time. To solve the problem caused by CPU sleep, we can use hold lock to keep the CPU from sleeping.
For example, you can use this tool class if you want to collect the temperature of mobile phones all day long.
If the CPU lock is not released, the standby power consumption will be high
2. use
2.0 need to configure permissions
<uses-permission android:name="android.permission.WAKE_LOCK" />
2.1 lock
public static void acquireCpuWakeLock(Context context) {
if (sCpuWakeLock != null) {
return;
}
sCpuWakeLock = createPartialWakeLock(context);
// Step 3: acquire() obtains the corresponding lock
sCpuWakeLock.acquire();
}
2.2 release lock
public static void releaseCpuLock() {
if (sCpuWakeLock != null) {
// Finally: release release
sCpuWakeLock.release();
sCpuWakeLock = null;
}
}
2.3 complete source code
package com.li.temperature.chart.util;
import android.content.Context;
import android.os.PowerManager;
/*
Flag Value CPU Screen Keyboard
PARTIAL_WAKE_LOCK On Off Off
SCREEN_DIM_WAKE_LOCK On Dim Off
SCREEN_BRIGHT_WAKE_LOCK On Bright Off
FULL_WAKE_LOCK On Bright Bright
*/
public class AlertWakeLock {
private static final String TAG = "AlertWakeLock";
private static PowerManager.WakeLock sCpuWakeLock;
static PowerManager.WakeLock createPartialWakeLock(Context context) {
// Step 1: get an instance of PowerManager
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
if (null == pm) {
return null;
}
// Step 2: call newWakeLock method in PowerManager to create a WakeLock object
return pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
// return pm.newWakeLock(PowerManager.FULL_WAKE_LOCK |
// PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.ON_AFTER_RELEASE,
// TAG);
}
public static void acquireCpuWakeLock(Context context) {
if (sCpuWakeLock != null) {
return;
}
sCpuWakeLock = createPartialWakeLock(context);
// Step 3: acquire() obtains the corresponding lock
sCpuWakeLock.acquire();
}
public static void releaseCpuLock() {
if (sCpuWakeLock != null) {
// Finally: release release
sCpuWakeLock.release();
sCpuWakeLock = null;
}
}
}