I'm following the developer guide for Lock Task Mode. It's clear for the most part, but I think needs a bit of work in some areas.
It seems to provide instructions on the presumption that you're starting another activity, though it does mention restarting one in the foreground:
"In Android 9.0 (API level 28) or higher, you can start another app’s activity in lock task mode. If an activity is already running in the foreground or background, you need to relaunch the activity. Call ActivityOptions.setLockTaskEnabled() and supply these options when starting the activity."
So what I'm trying to achieve is that when my MainActivity's fragment resumes for the first time, it checks if Lock Task Mode is enabled, and if it isn't, it turns it on. I use the following code, from one of the link's samples, to make the check:
private fun lockTaskModeNotRunning(): Boolean {
// Check if this app is in lock task mode. Screen pinning doesn't count.
var isLockTaskModeRunning = false
val activityManager = context
?.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
isLockTaskModeRunning = activityManager.lockTaskModeState == ActivityManager.LOCK_TASK_MODE_LOCKED
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
// Deprecated in API level 23.
isLockTaskModeRunning = activityManager.isInLockTaskMode
}
return !isLockTaskModeRunning
}
And I restart the app as described in the above quote. But this code infinitely runs because the line activityManager.lockTaskModeState == ActivityManager.LOCK_TASK_MODE_LOCKED is always false. lockTaskModeState is always set to LOCK_TASK_MODE_NONE, even after starting the activity with setLockTaskEnabled as true. The deprecated field, activityManager.isInLockTaskMode, is also always false.
I must be missing something pretty straight forward. The weird part is, if I stop code execution, the app is indeed in Lock Task Mode (only back button appears, can't go to homescreen).
I'll post my fragment's onResume code as it's relevant too:
override fun onResume() {
super.onResume()
val context = requireContext()
val devicePolicyManager = context.getSystemService(Context.DEVICE_POLICY_SERVICE)
as DevicePolicyManager
val deviceAdminReceiver = ComponentName(context, MyDeviceAdminReceiver::class.java)
devicePolicyManager.setLockTaskPackages(deviceAdminReceiver, APP_PACKAGES)
if (devicePolicyManager.isLockTaskPermitted(KIOSK_PACKAGE)) {
// Set an option to turn on lock task mode when starting the activity.
val options = ActivityOptions.makeBasic()
options.setLockTaskEnabled(true)
if (lockTaskModeNotRunning()) {
// Start our kiosk app's main activity with our lock task mode option.
val packageManager = context.packageManager
val launchIntent = packageManager.getLaunchIntentForPackage(KIOSK_PACKAGE)
if (launchIntent != null) {
context.startActivity(launchIntent, options.toBundle())
}
}
}
}