Method for keeping Android Service running after mobile phone sleep

  • 2021-08-28 21:17:47
  • OfStack

Recently, service was used for timing in the project, and it was normal when USB was connected. However, after unplugging USB, it was found that service stopped working after the mobile phone went to sleep. Finally, through PowerManager. WakeLock, cpu is kept awake after the screen is dormant to make service continue to run.

Official website reminds: This API will increase power consumption, so try not to use it unless necessary. If you want to use, try to use the lowest level and release the resource after exiting.

There are four grades of wake lock1:

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

Because you only need to keep cpu awake in your project, use PARTIAL_WAKE_LOCK.

Used in service as follows:


...
private PowerManager.WakeLock wakeLock = null;
...
@Override
public void onCreate() {
 super.onCreate();
 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
 wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TimerService.class.getName());
 wakeLock.acquire();
}
...
@Override
public void onDestroy() {
 if (wakeLock != null) {
  wakeLock.release();
  wakeLock = null;
 }
 super.onDestroy();
}

Related articles: