android - 为什么 FLAG_KEEP_SCREEN_ON 不能正常工作?

标签 android android-intent android-notifications android-notification-bar

当我的测试应用程序在前台运行持续通知时,我试图让屏幕始终处于开启状态。
当应用程序处于恢复状态时它工作正常,但是当我点击主页/中间按钮以将应用程序置于暂停状态同时在通知状态栏中显示正在进行的通知时它不起作用。

为什么getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)在前台/暂停状态下不起作用?

主要 Activity :

@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());
}

最佳答案

你应该移动 getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)下面setContentView()并把 android:keepScreenOn="true"进入主布局的 Root View 。

有关此主题的文档可能有用:https://developer.android.com/training/scheduling/wakelock.html#screen

关于android - 为什么 FLAG_KEEP_SCREEN_ON 不能正常工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27384378/

相关文章:

android - 带有 AlarmManager 的 IntentService

Android ndk-build 命令不执行任何操作

java - 创建 XML 的 Java 类有效,但在嵌入到 Android 应用程序时出现异常

android - 如何使用主页小部件启动 Activity

android - 多次调用的服务自行结束

android - 通知服务在通知点击上增加了额外的费用,怎么样?

android - 从 Android Widget 获取资源

android - java.lang.NoSuchMethodError : android. 应用程序.PendingIntent.getActivity

android - 无法在 Android 8 中禁用通知振动

android - 响应通知后按下后退按钮返回上一屏幕