Heshan Perera
Heshan Perera

Reputation: 4630

Android: Device Admin: Start Device Admin From Service

I am unable to get the Activity which allows the user to grant permission for an app to be a device admin to work.

My code is as follows...

ComponentName comp = new ComponentName(this, CustomReceiver.class);

Intent i = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);

i.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, comp);
i.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "Explanation");

startActivity(i);

The application does not crash / report an exception. What could I be doing wrong ?

Upvotes: 4

Views: 4895

Answers (2)

Patrick
Patrick

Reputation: 35232

Here is a clear example on how to do it, (the official docs here and here miss some context)

//class that implements DeviceAdminReceiver, defined in the Manifest 
ComponentName deviceAdminCN = new ComponentName(context, DeviceAdminReceiverImpl.class) 

...

Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, deviceAdminCN);
intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "your explanation for the user here");
startActivityForResult(intent, YOUR_REQUEST_CODE);

Here is the reference class used in the official sample app.

Upvotes: 1

nithinreddy
nithinreddy

Reputation: 6197

Something like this would do

if (!mPolicy.isAdminActive()) {

    Intent activateDeviceAdminIntent =
        new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);

    activateDeviceAdminIntent.putExtra(
        DevicePolicyManager.EXTRA_DEVICE_ADMIN,
        mPolicy.getPolicyAdmin());

    // It is good practice to include the optional explanation text to
    // explain to user why the application is requesting to be a device
    // administrator. The system will display this message on the activation
    // screen.
    activateDeviceAdminIntent.putExtra(
        DevicePolicyManager.EXTRA_ADD_EXPLANATION,
        getResources().getString(R.string.device_admin_activation_message));

    startActivityForResult(activateDeviceAdminIntent,
        REQ_ACTIVATE_DEVICE_ADMIN);
}

May be you are not considering

mPolicy.getPolicyAdmin()

Upvotes: 1

Related Questions