In a small MDM (Device Manager) app, we're trying to achieve the following functionality: Have the "Activate Device Manger" dialog popup as soon as the app is installed. This app must be installed on many devices using ADB in an enterprise setting, and it greatly would streamline the installation process if this functionality can be achieved. Using this code (Our DeviceAdminReceiver
is called by the same name, DeviceAdminReceiver
) to pop up the prompt:
public class PackageReceiver extends BroadcastReceiver {
private static final String PACKAGE_STRING = "package:";
private static final String REPLACEMENT_STRING = "";
@Override
public void onReceive(Context context, Intent intent) {
try{
boolean isSelf = intent.getDataString()
.replace(PACKAGE_STRING,REPLACEMENT_STRING)
.equals(BuildConfig.APPLICATION_ID);
switch (intent.getAction()){
case Intent.ACTION_PACKAGE_ADDED : case Intent.ACTION_PACKAGE_REPLACED :
if (isSelf){
Intent activateMDM =
new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
activateMDM.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
activateMDM.putExtra(
DevicePolicyManager.EXTRA_DEVICE_ADMIN,
DeviceAdminReceiver.getComponent(context)
);
context.startActivity(activateMDM);
}
break;
}
}catch (Exception e){
e.printStackTrace();
}
}
With this declaration in the manifest:
<receiver android:name=".receivers.PackageReceiver" android:enabled="true" android:exported="true">
<intent-filter>
<category android:name="android.intent.category.DEFAULT" />
<action android:name="android.intent.action.PACKAGE_ADDED" />
<action android:name="android.intent.action.PACKAGE_CHANGED" />
<action android:name="android.intent.action.PACKAGE_INSTALL" />
<action android:name="android.intent.action.PACKAGE_REPLACED" />
<action android:name="android.intent.action.PACKAGE_RESTARTED" />
<action android:name="android.intent.action.PACKAGES_UNSUSPENDED" />
<action android:name="android.intent.action.PACKAGES_SUSPENDED" />
<data android:scheme="package" />
</intent-filter>
</receiver>
The problem is that this code causes the prompt to flash when the install completes, but it does not stay open long enough for user to even tap 'activate'.
Based on the docs, we've added the line activateMDM.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
because without it the prompt didn't open at all, but after adding this line it only flashes momentarily and does not stay open.
If we use an implicit intent in the BroadcastReceiver
to open an activity
in our app and then have that activity
call the activateMDM
intent as above, we achieve the desired functionality. However it seems overkill to have an empty activity
dedicated for just this. How can the above code be edited to cause the "Activate Device Manager" prompt to display in the manner described above, and why does our code only cause it to flash and not stay open?