Android基础|后台服务中弹出激活设备管理器界面失败原因定位

公司项目部分功能要借助设备管理器实现,因此后台轮询判断是否激活设备管理器,没有的话就跳转到激活设备管理器界面。
但是发现后台服务中跳转激活设备管理器界面一直闪退,查了好久定位到原因:

E:\android-6.0.0_r1\frameworks\base\core\java\android\app\ContextImpl.java
因为后台服务中启动Activity添加了判断: @Override public void startActivity(Intent intent, Bundle options) { warnIfCallingFromSystemProcess(); if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_TASK) == 0) { throw new AndroidRuntimeException( "Calling startActivity() from outside of an Activity " + " context requires the FLAG_ACTIVITY_NEW_TASK flag." + " Is this really what you want?"); } mMainThread.getInstrumentation().execStartActivity( getOuterContext(), mMainThread.getApplicationThread(), null, (Activity) null, intent, -1, options); } 必须放入新的任务栈中才不会报异常。但是在 android源码中E:\android-6.0.0_r1\packages\apps\Settings\src\com\android\settings\DeviceAdminAdd.java 跳转到设备管理器中有这个判断: if ((getIntent().getFlags()&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) { Log.w(TAG, "Cannot start ADD_DEVICE_ADMIN as a new task"); finish(); return; } 因此只能在Activity中启动StartActivity跳转到设备管理器的激活界面。
【Android基础|后台服务中弹出激活设备管理器界面失败原因定位】

    推荐阅读