在Android上以编程方式打开屏幕

时间:2015-05-07 01:50:07

标签: android screen powermanager

当用户使用电源按钮关闭时,我需要以编程方式打开屏幕,是的我在Activity中始终有正确的标志以保持屏幕开启,但它不会避免用户按下电源按钮。

到目前为止,我找到了一个解决方案,但它使用的是已弃用的唤醒锁

sWakeLock = sPM.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.ON_AFTER_RELEASE, TAG_WAKELOCK);

sWakeLock.acquire();
sWakeLock.release();

有更好的方法来实现它吗?

3 个答案:

答案 0 :(得分:12)

在棒棒糖中你可能想要添加更多标志:

final Window win = getWindow();
    win.addFlags( WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED |
            WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD |
            WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON |
            WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON |
            WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON );

我从AOSP https://android.googlesource.com/platform/packages/apps/DeskClock/+/dfd1960/src/com/android/deskclock/alarms/AlarmActivity.java

得到了这个

答案 1 :(得分:3)

这是从活动中打开屏幕的最新方法:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
    this.setTurnScreenOn(true);
} else {
    final Window window = getWindow();
    window.addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
}

使用FLAG_TURN_SCREEN_ON,但此标志在API级别27中已被弃用,因此请从API级别27开始使用Activity.setTurnScreenOn(true)

答案 2 :(得分:2)

代码

 PowerManager powerManager = (PowerManager) context.getSystemService(context.POWER_SERVICE);
    PowerManager.WakeLock  wakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK |
            PowerManager.ACQUIRE_CAUSES_WAKEUP |
            PowerManager.ON_AFTER_RELEASE, "appname::WakeLock");

    //acquire will turn on the display
    wakeLock.acquire();

    //release will release the lock from CPU, in case of that, screen will go back to sleep mode in defined time bt device settings
    wakeLock.release();

在清单文件中,权限应为

<uses-permission android:name="android.permission.WAKE_LOCK"/>