在一个小型 MDM(设备管理器)应用程序中,我们试图实现以下功能: 安装应用程序后立即弹出“激活设备管理器”对话框。此应用程序必须在企业环境中使用 ADB 安装在许多设备上,如果可以实现此功能,它将大大简化安装过程。使用这段代码(OurDeviceAdminReceiver
同名,DeviceAdminReceiver
)弹出提示:
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();
}
}
在清单中使用此声明:
<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>
问题是此代码会在安装完成时导致提示闪烁,但它没有保持打开足够长的时间,用户甚至无法点击“激活”。
根据docs,我们添加了该行activateMDM.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
,因为没有它,提示根本不会打开,但是在添加该行之后,它只会短暂闪烁并且不会保持打开状态。
如果我们在应用程序中使用隐式意图BroadcastReceiver
打开activity
应用程序,然后像上面那样activity
调用activateMDM
意图,我们就可以实现所需的功能。activity
然而,为此专门有一个空的专用空间似乎过大了。上面的代码怎么编辑才能使“激活设备管理器”提示以上述方式显示,为什么我们的代码只导致它闪烁而不保持打开状态?