//Android关掉屏幕,需要用PowerManager ,并声明相关权限。
-
获取电源管理器PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
-
设置相关api
pm.goToSleep(SystemClock.uptimeMillis());
PowerManager.WakeLock wakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "TAG");
-
wakeLock.acquire();
-
wakeLock.release();
//关闭 屏幕常亮功能
if(wakeLock != null && wakeLock .isHeld()){
wakeLock .release();
wakeLock = null;
}
//Android启用屏幕常亮功能
PowerManager pm =(PowerManager) getSystemService(POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK| PowerManager.ACQUIRE_CAUSES_WAKEUP, myPowerManager.TAG);
wakeLock.acquire();
声明相关权限
<uses-permission android:name="android.permission.WAKE_LOCK" />
<user-permission android:name="android.permission.DEVICE_POWER"/>
关于int flags 各种锁的类型对CPU 、屏幕、键盘的影响:
PARTIAL_WAKE_LOCK :保持CPU 运转,屏幕和键盘灯有可能是关闭的。
SCREEN_DIM_WAKE_LOCK :保持CPU 运转,允许保持屏幕显示但有可能是灰的,允许关闭键盘灯
SCREEN_BRIGHT_WAKE_LOCK :保持CPU 运转,允许保持屏幕高亮显示,允许关闭键盘灯
FULL_WAKE_LOCK :保持CPU 运转,保持屏幕高亮显示,键盘灯也保持亮度.
WindowManager.LayoutParams params = getWindow().getAttributes();
params.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
params.screenBrightness = 0;
getWindow().setAttributes(params);