Launch DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN intent from service

I have a service, and I want the service to contribute to its inclusion as Device Admin, so far I have run such user interface interactions from the service, for example

    Intent intent2 = new Intent();
    intent2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent2.setAction(android.content.Intent.ACTION_VIEW);
    intent2.setDataAndType(uri, "application/vnd.android.package-archive");
    context.startActivity(intent2);

and it works, but with DevicePolicyManager I cannot find a way:

        Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, mAdminName);
        intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION,  "some text.");
        context.startActivity(intent);

doesn't work: don't advertise anything, but don't crash either. Without intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);This is simply a failure, because this code is inside the tread inside the service. Ideas?

+6
source share
3 answers

I just fixed this issue for myself.

Please note that you need to put this code inside the parent into the 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 :)

+4
source

Android DeviceAdminAdd:

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

DevicePolicyManager.

+6

You do not even need to pop up the security settings of the device administrator interface. Here is a way to do it pragmatically:

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

where you must specify the recipient in the manifest, as described in the Android Developer's Guide:
Device Administration Overview

Tested with Android 6.0

David

-1
source

All Articles