Alan Haverty Alan Haverty - 4 months ago 30
Android Question

Toggling FLAG_KEEP_SCREEN_ON at specific times

I'm trying to toggle the

flag programmatically. My android tablet app is intended for a specific work environment where my application's main activity will always be on.

We have gotten by so far by using


in the layout xml.

Unfortunately, the employees don't always remember to manually turn off the screen at the end of the work day. I want to programmatically disable the 'keep screen on' functionality once the work day is over, but re-enable it once it starts again.

I'm thinking I can use a Task/
in my
that runs every x minutes and checks whether the current time is within the bounds or not. I also plan on cancelling the task

My question: Is there a better way? Or is this a good approach? If this is, should I be using a looper?


You could just use AlarmManager to set the flag at the appropriate time, no need to check periodically.

For example, define a BroadcastReceiver in your Activity, that clears the FLAG_KEEP_SCREEN_ON flag:

private static final String ACTION_SCREEN_OFF = "yourpackagename.ACTION_SCREEN_OFF";

private final BroadcastReceiver screenOffReceiver = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {

Register/unregister it dynamically:

protected void onResume() {
    registerReceiver(screenOffReceiver, new IntentFilter(ACTION_SCREEN_OFF));

protected void onPause() {

And set an alarm that triggers this receiver at the appropriate time (16:00 every day in this example):

Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 16);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);

AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);

Intent intent = new Intent(ACTION_SCREEN_OFF);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent,
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
    AlarmManager.INTERVAL_DAY, pendingIntent);