FLAG_TURN_SCREEN_ON does not always work

shelll picture shelll · Mar 31, 2012 · Viewed 10.8k times · Source

i start an activity from a BroadcastReceiver, which is triggered by an alaram (RTC_WAKEUP type). in onCreate of that activity i add these flags

getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD |
    WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED |
    WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON |
    WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON        
);

problem is that sometimes (approximately 10% cases) the screen does not turn on. the alarm is correctly triggered (i here the sound of a notification, which is also fired in the receiver's onReceive(). then, if i hit the phone's power button, the screen turns on, showing my activity, and instantly turns off. after that, the power button works good. this happen on android 2.3.7 and here is the onReceive() method

@Override
public void onReceive(Context context, Intent intent) {
    m_Context = context;

    Bundle extras = intent.getExtras();
    final int id = extras.getInt("timer_id");

    Intent activityIntent = new Intent(m_Context, MyActivity.class);
    activityIntent.putExtra("timer_id", id);
    activityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    m_Context.startActivity(activityIntent);

    // and now load the alarm sound and play it for the desired time
    showFinishedNotification();
}

i would like to avoid using PowerManager, as it needs a permission, and the flags are the prefered way.

what could be a problem? logcat does not show any problems...

Answer

Camilo Tejeiro picture Camilo Tejeiro · May 16, 2016

From my experience and research on this topic:

  • The FLAG_TURN_SCREEN_ON can not be used to turn the screen ON and OFF multiple times in your application.

  • The FLAG_TURN_SCREEN_ON can only be used once to turn the screen ON when creating a new activity (preferably in the onCreate() method) or when re-creating a view.

Now, you can get around this limitation by:

  • Launching a new activity and setting the flag there, then finishing the activity (by the user or programmatically) to let the screen turn off.
  • Setting the params.screenBrightness parameters to as "dim" as possible, sometimes the screen "appears OFF". You can then increase the brightness to "turn ON" the screen. However, this often does not work as the screen is still dim but visible, also this doesn't work if the user locks the phone.
  • Using the Power Manager Wakelock (this still works but Android deprecated this functionality, so they are discouraging the use of this technique). However, as far as I can tell this is the only way I can get my application to turn the screen ON/OFF reliably.

None of these are ideal (in fact they feel like hacks) but just use the one that better suits your application needs.

You can read more here: