I\'ve got an app that registers itself as the default launcher and pins itself automatically when started.
This all works fine when installing the app. It pins itself a
I had the same problem and I could really only find one solution. I'm not sure why but yeah, something in android prevents task locking when booting up which boggles my mind since the task lock was designed to create these "kiosk" type of applications. The only solution I could find was to detect for a case when it didn't lock then restart the application. Its a little "hacky" but what else can you do?
To detect for the case where it didn't lock I created a state variable and assigning states (Locking, Locked, Unlocking, Unlocked). Then in the device admin receiver in onTaskModeExiting if the state isn't "Unlocking" then I know it unlocked on its own. So if this case happened where it failed, I then restart the application using this method (which schedules the application in the alarm manager then kills the application):
how to programmatically "restart" android app?
Here is some 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 it should hopefully get you pointed towards a solution.