I had the same problem and I really could only find one solution. I’m not sure why, but yes, something in the android prevents the task blocking at boot, which makes me wise, because the task block was designed to create these kiosk-like applications. The only solution I could find was to detect the case when it is not locked, and then restart the application. Its a bit “hacked,” but what else can you do?
To detect a case when it is not locked, I created a state variable and assigning states (lock, lock, unlock, unlock). Then in the device administrator's receiver in onTaskModeExiting, if the state is not “unlock”, then I know that it is unlocked by itself. Therefore, if this incident occurred where it failed, I restarted the application using this method (which plans the application in the alarm manager then kills the application):
how to programmatically restart the "Android app?
Here is a sample code:
DeviceAdminReceiver
@Override public void onLockTaskModeEntering(Context context, Intent intent, String pkg) { super.onLockTaskModeEntering(context, intent, pkg); Lockdown.LockState = Lockdown.LOCK_STATE_LOCKED; } @Override public void onLockTaskModeExiting(Context context, Intent intent) { super.onLockTaskModeExiting(context, intent); if (Lockdown.LockState != Lockdown.LOCK_STATE_UNLOCKING) { MainActivity.restartActivity(context); } Lockdown.LockState = Lockdown.LOCK_STATE_UNLOCKED; }
Mainactivity
public static void restartActivity(Context context) { if (context != null) { PackageManager pm = context.getPackageManager(); if (pm != null) { Intent intent = pm.getLaunchIntentForPackage(context.getPackageName()); if (intent != null) { intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); int pendingIntentId = 223344; PendingIntent pendingIntent = PendingIntent.getActivity(context, pendingIntentId, intent, PendingIntent.FLAG_CANCEL_CURRENT); AlarmManager mgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE); mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, pendingIntent); System.exit(0); } } } } private void lock() { Lockdown.LockState = Lockdown.LOCK_STATE_LOCKING; startLockTask(); } private void unlock() { ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); if (am.getLockTaskModeState() == ActivityManager.LOCK_TASK_MODE_LOCKED) { Lockdown.LockState = Lockdown.LOCK_STATE_UNLOCKING; stopLockTask(); } }
In truth, this is a simplified version of what I implemented. But we hope you point to a solution.
Will young
source share