Alan Haverty Alan Haverty - 1 month ago 15
Android Question

Toggling FLAG_KEEP_SCREEN_ON at specific times

I'm trying to toggle the

FLAG_KEEP_SCREEN_ON
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

android:keepScreenOn="true"


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/
handler.postDelayed()
in my
onResume()
that runs every x minutes and checks whether the current time is within the bounds or not. I also plan on cancelling the task
onPause()
.

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

Answer

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() {
    @Override
    public void onReceive(Context context, Intent intent) {
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }
};

Register/unregister it dynamically:

@Override
protected void onResume() {
    super.onResume();
    registerReceiver(screenOffReceiver, new IntentFilter(ACTION_SCREEN_OFF));
}

@Override
protected void onPause() {
    unregisterReceiver(screenOffReceiver);
    super.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,
    PendingIntent.FLAG_UPDATE_CURRENT);
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
    AlarmManager.INTERVAL_DAY, pendingIntent);
Comments