I'm developing a mission-critical application for an Android Tablet.
I'd like to foolproof the application, specifically to prevent the user from shutting down the app or turning the screen off during some important processes, which take some time.
For preventing the user from exiting or hiding the app, there's Lock task mode.
After searching on SO, I found that this is probably not possible is not really possible - however that answer is from 2012 - Is this still the case?
Meanwhile, I did implement the workaround of turning requesting to turn the screen back on if the ACTION_SCREEN_OFF
intent is detected, described here, but it's fairly ugly, and also the keyguard is sometimes disabled and sometimes not, I'm not sure why.
Here's my code:
override fun onReceive(context: Context?, intent: Intent) {
if (intent.action == Intent.ACTION_SCREEN_OFF) {
Log.i(LOG_TAG, "Screen off was detected, requesting to turning the screen back on...")
// Disable key lock, so keygoard will not be shown once the screen light back up
val keyguardManager = getSystemService(KEYGUARD_SERVICE) as KeyguardManager
keyguardManager.requestDismissKeyguard(this@MainActivity, null)
// Ask to turn the screen back on - lifted from here
// https://stackoverflow.com/a/10143686/4574731
// Ask device to keep screen awake
val powerManager = getSystemService(POWER_SERVICE) as PowerManager
val wakeLock = powerManager.newWakeLock(
PowerManager.SCREEN_DIM_WAKE_LOCK or PowerManager.ACQUIRE_CAUSES_WAKEUP or PowerManager.ON_AFTER_RELEASE,
"rpicapp:turnScreenOnReciever"
)
wakeLock.acquire(10*1000L /* 10 seconds */)
try {
// Broadcast the ACTION_SCREEN_ON intent after 10 milliseconds
val alarmMgr = getSystemService(ALARM_SERVICE) as AlarmManager
val screenOnIntent = PendingIntent.getActivity(context, 0, Intent(Intent.ACTION_SCREEN_ON), 0)
alarmMgr[AlarmManager.ELAPSED_REALTIME_WAKEUP, 10] = screenOnIntent
} finally {
wakeLock.release()
}
}
}
Is there a better workaround for this in 2021?
Thanks