Run intent DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN from a service

守給你的承諾、 提交于 2019-12-01 17:48:49

I've just fixed such issue for myself.

Note, that you need to put this code inside parent in Android Manifest.xml file:

    <receiver
        android:name=".ScreenLockerDeviceAdminReceiver"
        android:permission="android.permission.BIND_DEVICE_ADMIN" >
        <meta-data
            android:name="android.app.device_admin"
            android:resource="@xml/device_admin_policies" />

        <intent-filter>
            <action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
        </intent-filter>
    </receiver>

and it works :)

The reason is on the code of the Android DeviceAdminAdd class itself:

if ((getIntent().getFlags()&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
            Log.w(TAG, "Cannot start ADD_DEVICE_ADMIN as a new task");
            finish();
            return;
       }

You should consider using another activity to call the DevicePolicyManager.

You don't even need to popup security setting's device admin UI. Here is a way to do it pragmatically:

Runtime.getRuntime("dpm set-device-admin --user 0 com.mydeviceadmin/.deviceAdminReceiver")  

where receiver needs to be define in manifest as described in android developer guide:
Device administration overview

Tested with android 6.0

David

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!