简体   繁体   中英

Why FLAG_KEEP_SCREEN_ON doesn't work properly?

I am trying to make the screen to be always on while my test app is in the foreground with Ongoing Notification running. It works fine when the app is on resume state, but it doesn't work when I hit the home/middle button to put the app on pause state while showing up the Ongoing notification in the notification status bar.

Why getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) does not work in the foreground/pause state?

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

I have done this already in one of my app and it works perfectly for me.

Plese follow these steps properly.

Step 1:

@Override
protected void onCreate(Bundle bundle) {
    super.onCreate(bundle);    
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}

Step 2: Now you need to put set screen on,

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    View view = getLayoutInflater().inflate(R.layout.layout_activity, null);
    view.setKeepScreenOn(true);
    setContentView(view);
}

You can also add it to the root of your XML layout.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:keepScreenOn="true" >

I followed these steps and it seems to work perfectly for me.

You should move getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) below setContentView() and put android:keepScreenOn="true" into the root View of your main layout .

The documentation on this topic might be usefull: https://developer.android.com/training/scheduling/wakelock.html#screen

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM