为什么FLAG_KEEP_SCREEN_ON无法正常工作?

4
我正在尝试在我的测试应用程序位于前台并且持续通知运行时使屏幕始终保持开启状态。当应用程序处于恢复状态时,它运行良好,但在显示持续状态栏通知的同时按下主页/中间按钮将应用程序置于暂停状态时,它不起作用。
为什么在前台/暂停状态下 getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) 不起作用?
MainActivity:
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

    setContentView(R.layout.main);

    ...

    NotificationCompat.Builder OnGoingStatusBar = new NotificationCompat.Builder(this);
    OnGoingStatusBar.setSmallIcon(R.drawable.image);
    OnGoingStatusBar.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher));            
    OnGoingStatusBar.setTicker(Test);           
    OnGoingStatusBar.setContentTitle("Test");
    OnGoingStatusBar.setContentText("Testing Message");         
    OnGoingStatusBar.setWhen(System.currentTimeMillis());
    OnGoingStatusBar.setAutoCancel(false);
    OnGoingStatusBar.setContent(notificationView).build();
    OnGoingStatusBar.setOngoing(true);   //Create OnGoing Status Bar
    OnGoingStatusBar.setPriority(Notification.PRIORITY_MAX);
    NotificationManager.notify(STATUSBAR_ID, OnGoingStatusBar.build());
}

只有当应用程序有窗口时才能正常工作,即用户可以看到其用户界面。 - StoneBird
getWindow()。只有在可见时才有窗口。 - njzk2
感谢您的回复。有没有任何解决方法可以实现我的目标?我知道这适用于旧版Android: pm =(PowerManager)getSystemService(Context.POWER_SERVICE); km =(KeyguardManager)getSystemService(Context.KEYGUARD_SERVICE); mKeyguardLock = km.newKeyguardLock(“INFO”); mWakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.ON_AFTER_RELEASE,“INFO”);mKeyguardLock.disableKeyguard(); //取消键盘锁 mWakeLock.acquire(); - YRTM2014
哎呀,这段代码在注释部分看起来不太好。 - YRTM2014
1个回答

2

谢谢您的评论。我遵循了您的建议,但没有改变。屏幕仍然会在活动不可见 / 前台 / onPause状态时关闭。谢谢。 - YRTM2014
@YRTM2014 你正在描述预期的功能。请参阅https://developer.android.com/training/scheduling/wakelock.html。 - Abandoned Cart
1
KeepScreenOn 对我来说并没有起作用,它仍然会进入睡眠状态。 - Ted

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接