首先,在Activity里添加一下代码:
成员变量:
private PowerManager.WakeLock wakeLock = null;
重写父类Activity的两个方法并添加一下逻辑:
@Override
public void onResume() {
super.onResume();
acquireWakeLock(this);
}
@Override
public void onPause() {
super.onPause();
releaseWakeLock();
}
public void acquireWakeLock(Context context) {
if (wakeLock == null) {
PowerManager powerManager = (PowerManager) (context
.getSystemService(Context.POWER_SERVICE));
wakeLock = powerManager.newWakeLock(
PowerManager.SCREEN_DIM_WAKE_LOCK, "My Tag");
wakeLock.acquire();
}
}
public void releaseWakeLock() {
if (wakeLock != null && wakeLock.isHeld()) {
wakeLock.release();
wakeLock = null;
}
}
然后,在AndroidManifest.xml里添加如下权限即可: