DeviceAdminReceiver
DevicePolicyManager
DeviceAdminInfo
Android 2.2 introduces support for enterprise applications by offering theAndroid Device Administration API. The Device Administration API provides deviceadministration features at the system level. These APIs allow you to createsecurity-aware applications that are useful in enterprise settings, in which ITprofessionals require rich control over employee devices. For example, thebuilt-in Android Email application has leveraged the new APIs to improveExchange support. Through the Email application, Exchange administrators canenforce password policies — including alphanumeric passwords or numericPINs — across devices. Administrators can also remotely wipe (that is,restore factory defaults on) lost or stolen handsets. Exchange users can synctheir email and calendar data.
This document is intended for developers who want to develop enterprisesolutions for Android-powered devices. It discusses the various featuresprovided by the Device Administration API to provide stronger security foremployee devices that are powered by Android.
Here are examples of the types of applications that might use the Device Administration API:
You use the Device Administration API to write device admin applications that usersinstall on their devices. The device admin application enforces the desiredpolicies. Here's how it works:
If users do not enable the device admin app, it remains on the device, but in an inactive state. Users will not be subject to its policies, and they will conversely not get any of the application's benefits—for example, they may not be able to sync data.
If a user fails to comply with the policies (for example, if a user sets apassword that violates the guidelines), it is up to the application to decidehow to handle this. However, typically this will result in the user not beingable to sync data.
If a device attempts to connect to a server that requires policies notsupported in the Device Administration API, the connection will notbe allowed. The Device Administration API does not currently allow partialprovisioning. In other words, if a device (for example, a legacy device) doesnot support all of the stated policies, there is no way to allow thedevice to connect.
If a device contains multiple enabled admin applications, the strictest policy isenforced. There is no way to target a particular adminapplication.
To uninstall an existing device admin application, users need tofirst unregister the application as an administrator.
In an enterprise setting, it's often the case that employee devices mustadhere to a strict set of policies that govern the use of the device. TheDevice Administration API supports the policies listed in Table 1.Note that the Device Administration API currently only supports passwords for screenlock:
Policy | Description |
---|---|
Password enabled | Requires that devices ask for PIN or passwords. |
Minimum password length | Set the required number of characters for the password. For example, youcan require PIN or passwords to have at least six characters. |
Alphanumeric password required | Requires that passwords have acombination of letters and numbers. They may include symbolic characters. |
Complex password required | Requires that passwords must contain at least a letter, a numerical digit, and a special symbol. Introduced in Android 3.0. |
Minimum letters required in password | The minimum number ofletters required in the password for all admins or a particular one. Introduced in Android 3.0. |
Minimum lowercase letters required in password | The minimum number of lowercase letters required in the password for all admins or a particular one. Introduced in Android 3.0. |
Minimum non-letter characters required in password | The minimum number ofnon-letter characters required in the password for all admins or a particular one. Introduced in Android 3.0. |
Minimum numerical digits required in password | The minimum number of numerical digits required in the password for all admins or a particular one. Introduced in Android 3.0. |
Minimum symbols required in password | The minimum number of symbols required in the password for all admins or a particular one. Introduced in Android 3.0. |
Minimum uppercase letters required in password | The minimum number of uppercase letters required in the password for all admins or a particular one. Introduced in Android 3.0. |
Password expiration timeout | When the password will expire, expressed as a delta in milliseconds from when a device admin sets the expiration timeout. Introduced in Android 3.0. |
Password history restriction | This policy prevents users from reusing the last n unique passwords. This policy is typically used in conjunction withsetPasswordExpirationTimeout() , which forcesusers to update their passwords after a specified amount of time has elapsed.Introduced in Android 3.0. |
Maximum failed password attempts | Specifies how many times a user can enter the wrong password before thedevice wipes its data. The Device Administration API also allows administrators toremotely reset the device to factory defaults. This secures data in case thedevice is lost or stolen. |
Maximum inactivity time lock | Sets the length of time since the user last touched the screen orpressed a button before the device locks the screen. When this happens, usersneed to enter their PIN or passwords again before they can use their devices andaccess data. The value can be between 1 and 60 minutes. |
Require storage encryption | Specifies that the storage area should be encrypted, if the device supports it. Introduced in Android 3.0. |
In addition to supporting the policies listed in the above table, the DeviceAdministration API lets you do the following:
The examples used in this document are based on the Device Administration APIsample, which is included in the SDK samples. For information on downloading andinstalling the SDK samples, seeGetting the Samples. Here is thecomplete code forthe sample.
Thesample application offers a demo of device admin features. It presents userswith a user interface that lets them enable the device admin application. Oncethey've enabled the application, they can use the buttons in the user interfaceto do the following:
System administrators can use the Device Administration API to write an applicationthat enforces remote/local device security policy enforcement. This sectionsummarizes the steps involved in creating a device administrationapplication.
To use the Device Administration API, the application'smanifest must include the following:
DeviceAdminReceiver
that includes the following:
BIND_DEVICE_ADMIN
permission.ACTION_DEVICE_ADMIN_ENABLED
intent, expressed in the manifest as an intent filter.Here is an excerpt from the Device Administration sample manifest:
<activity android:name=".app.DeviceAdminSample$Controller" android:label="@string/activity_sample_device_admin"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.SAMPLE_CODE" /> </intent-filter> </activity> <receiver android:name=".app.DeviceAdminSample" android:label="@string/sample_device_admin" android:description="@string/sample_device_admin_description" android:permission="android.permission.BIND_DEVICE_ADMIN"> <meta-data android:name="android.app.device_admin" android:resource="@xml/device_admin_sample" /> <intent-filter> <action android:name="android.app.action.DEVICE_ADMIN_ENABLED" /> </intent-filter> </receiver>
Note that:
Activity
subclass calledController
. The syntax".app.DeviceAdminSample$Controller"
indicates thatController
is an inner class that is nested inside theDeviceAdminSample
class. Note that an Activity does not need to bean inner class; it just is in this example.ApiDemos/res/values/strings.xml
. For more information about resources, seeApplication Resources.
android:label="@string/activity_sample_device_admin"
refers to theuser-readable label for the activity.android:label="@string/sample_device_admin"
refers to theuser-readable label for the permission.android:description="@string/sample_device_admin_description"
refers tothe user-readable description of the permission. A descripton is typically longer and moreinformative thana label.android:permission="android.permission.BIND_DEVICE_ADMIN"
is a permission that aDeviceAdminReceiver
subclass musthave, to ensure that only the system can interact with the receiver (no application can be granted this permission). Thisprevents other applications from abusing your device admin app.android.app.action.DEVICE_ADMIN_ENABLED
is the the primaryaction that aDeviceAdminReceiver
subclass must handle to beallowed to manage a device. This is set to the receiver when the user enablesthe device admin app. Your code typically handles this inonEnabled()
. To be supported, the receiver must alsorequire the BIND_DEVICE_ADMIN
permission so that other applicationscannot abuse it.android:resource="@xml/device_admin_sample"
declares the security policies used in metadata. The metadata provides additionalinformation specific to the device administrator, as parsed by theDeviceAdminInfo
class. Here are the contents ofdevice_admin_sample.xml
:<device-admin xmlns:android="http://schemas.android.com/apk/res/android"> <uses-policies> <limit-password /> <watch-login /> <reset-password /> <force-lock /> <wipe-data /> </uses-policies> </device-admin>
In designing your device administration application, you don't need toinclude all of the policies, just the ones that are relevant for your app.
For more discussion of the manifest file, see the Android Developers Guide.The Device Administration API includes the following classes:
DeviceAdminReceiver
DeviceAdminReceiver
subclass.
DevicePolicyManager
DeviceAdminReceiver
that the userhas currently enabled. The
DevicePolicyManager
manages policies forone or more
DeviceAdminReceiver
instances
DeviceAdminInfo
These classes provide the foundation for a fully functional device administration application.The rest of this section describes how you use theDeviceAdminReceiver
andDevicePolicyManager
APIs to write a device admin application.
To create a device admin application, you must subclassDeviceAdminReceiver
. TheDeviceAdminReceiver
classconsists of a series of callbacks that are triggered when particular eventsoccur.
In its DeviceAdminReceiver
subclass, the sample applicationsimply displays aToast
notification in response to particularevents. For example:
public class DeviceAdminSample extends DeviceAdminReceiver { ... @Override public void onEnabled(Context context, Intent intent) { showToast(context, "Sample Device Admin: enabled"); } @Override public CharSequence onDisableRequested(Context context, Intent intent) { return "This is an optional message to warn the user about disabling."; } @Override public void onDisabled(Context context, Intent intent) { showToast(context, "Sample Device Admin: disabled"); } @Override public void onPasswordChanged(Context context, Intent intent) { showToast(context, "Sample Device Admin: pw changed"); } void showToast(Context context, CharSequence msg) { Toast.makeText(context, msg, Toast.LENGTH_SHORT).show(); } ... }
One of the major events a device admin application has to handle is the userenabling the application. The user must explicitly enable the application forthe policies to be enforced. If the user chooses not to enable the applicationit will still be present on the device, but its policies will not be enforced, and the user will notget any of the application's benefits.
The process of enabling the application begins when the user performs anaction that triggers theACTION_ADD_DEVICE_ADMIN
intent. In thesample application, this happens when the user clicks theEnableAdmin button.
When the user clicks the Enable Admin button, the displaychanges to prompt the user to enable the device admin application, as shown in figure2.
Below is the code that gets executed when the user clicks the EnableAdmin button shown in figure 1.
private OnClickListener mEnableListener = new OnClickListener() { public void onClick(View v) { // Launch the activity to have the user enable our admin. Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN); intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, mDeviceAdminSample); intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "Additional text explaining why this needs to be added."); startActivityForResult(intent, RESULT_ENABLE); } }; ... // This code checks whether the device admin app was successfully enabled. @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case RESULT_ENABLE: if (resultCode == Activity.RESULT_OK) { Log.i("DeviceAdminSample", "Administration enabled!"); } else { Log.i("DeviceAdminSample", "Administration enable FAILED!"); } return; } super.onActivityResult(requestCode, resultCode, data); }
The lineintent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN,mDeviceAdminSample)
states thatmDeviceAdminSample
(which isa DeviceAdminReceiver
component) is the target policy.This line invokes the user interface shown in figure 2, which guides users throughadding the device administrator to the system (or allows them to reject it).
When the application needs to perform an operation that is contingent on thedevice admin application being enabled, it confirms that the application isactive. To do this it uses theDevicePolicyManager
methodisAdminActive()
. Notice that the DevicePolicyManager
methodisAdminActive()
takes aDeviceAdminReceiver
component as its argument:
DevicePolicyManager mDPM; ... boolean active = mDPM.isAdminActive(mDeviceAdminSample); if (active) { // Admin app is active, so do some admin stuff ... } else { // do something else }
DevicePolicyManager
is a public class for managing policiesenforced on a device.DevicePolicyManager
manages policies for oneor moreDeviceAdminReceiver
instances.
You get a handle to the DevicePolicyManager
as follows:
DevicePolicyManager mDPM = (DevicePolicyManager)getSystemService(Context.DEVICE_POLICY_SERVICE);
This section describes how to use DevicePolicyManager
to perform administrative tasks:
DevicePolicyManager
includes APIs for setting and enforcing thedevice password policy. In the Device Administration API, the password only applies toscreen lock. This section describes common password-related tasks.
This code displays a user interface prompting the user to set a password:
Intent intent = new Intent(DevicePolicyManager.ACTION_SET_NEW_PASSWORD); startActivity(intent);
The password quality can be one of the following DevicePolicyManager
constants:
PASSWORD_QUALITY_ALPHABETIC
PASSWORD_QUALITY_ALPHANUMERIC
PASSWORD_QUALITY_NUMERIC
PASSWORD_QUALITY_COMPLEX
PASSWORD_QUALITY_SOMETHING
PASSWORD_QUALITY_UNSPECIFIED
For example, this is how you would set the password policy to require an alphanumeric password:
DevicePolicyManager mDPM; ComponentName mDeviceAdminSample; ... mDPM.setPasswordQuality(mDeviceAdminSample, DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC);
Beginning with Android 3.0, the DevicePolicyManager
classincludes methods that let you fine-tune the contents of the password. Forexample, you could set a policy that states that passwords must contain at leastn uppercase letters. Here are the methods for fine-tuning a password'scontents:
setPasswordMinimumLetters()
setPasswordMinimumLowerCase()
setPasswordMinimumUpperCase()
setPasswordMinimumNonLetter()
setPasswordMinimumNumeric()
setPasswordMinimumSymbols()
For example, this snippet states that the password must have at least 2 uppercase letters:
DevicePolicyManager mDPM; ComponentName mDeviceAdminSample; int pwMinUppercase = 2; ... mDPM.setPasswordMinimumUpperCase(mDeviceAdminSample, pwMinUppercase);
You can specify that a password must be at least the specified minimumlength. For example:
DevicePolicyManager mDPM; ComponentName mDeviceAdminSample; int pwLength; ... mDPM.setPasswordMinimumLength(mDeviceAdminSample, pwLength);
You can set the maximum number of allowed failed password attempts before thedevice is wiped (that is, reset to factory settings). For example:
DevicePolicyManager mDPM; ComponentName mDeviceAdminSample; int maxFailedPw; ... mDPM.setMaximumFailedPasswordsForWipe(mDeviceAdminSample, maxFailedPw);
Beginning with Android 3.0, you can use the setPasswordExpirationTimeout()
method to set when a password will expire, expressed as a delta in milliseconds from when a device admin sets the expiration timeout. For example:
DevicePolicyManager mDPM; ComponentName mDeviceAdminSample; long pwExpiration; ... mDPM.setPasswordExpirationTimeout(mDeviceAdminSample, pwExpiration);
From the Device Administration API sample, here is the codethat updates the password expiration status:
DevicePolicyManager mDPM; ComponentName mDeviceAdminSample; private TextView mPasswordExpirationStatus; ... void updatePasswordExpirationStatus() { boolean active = mDPM.isAdminActive(mDeviceAdminSample); String statusText; if (active) { long now = System.currentTimeMillis(); // Query the DevicePolicyManager twice - first for the expiration values // set by the sample app, and later, for the system values (which may be different // if there is another administrator active.) long expirationDate = mDPM.getPasswordExpiration(mDeviceAdminSample); long mSecUntilExpiration = expirationDate - now; if (mSecUntilExpiration >= 0) { statusText = "Expiration in " + countdownString(mSecUntilExpiration); } else { statusText = "Expired " + countdownString(-mSecUntilExpiration) + " ago"; } // expirationTimeout is the cycle time between required password refresh long expirationTimeout = mDPM.getPasswordExpirationTimeout(mDeviceAdminSample); statusText += " / timeout period " + countdownString(expirationTimeout); // Now report the aggregate (global) expiration time statusText += " / Aggregate "; expirationDate = mDPM.getPasswordExpiration(null); mSecUntilExpiration = expirationDate - now; if (mSecUntilExpiration >= 0) { statusText += "expiration in " + countdownString(mSecUntilExpiration); } else { statusText += "expired " + countdownString(-mSecUntilExpiration) + " ago"; } } else { statusText = "<inactive>"; } mPasswordExpirationStatus.setText(statusText);
Beginning with Android 3.0, you can use the setPasswordHistoryLength()
method to limit users'ability to reuse old passwords. This method takes a lengthparameter, which specifies how many oldpasswords are stored. When this policy is active, users cannot enter a newpassword that matches the lastn passwords. This preventsusers from using the same password over and over. This policy is typically usedin conjunction withsetPasswordExpirationTimeout()
,which forces usersto update their passwords after a specified amount of time has elapsed.
For example, this snippet prohibits users from reusing any of their last 5 passwords:
DevicePolicyManager mDPM; ComponentName mDeviceAdminSample; int pwHistoryLength = 5; ... mDPM.setPasswordHistoryLength(mDeviceAdminSample, pwHistoryLength);
You can set the maximum period of user inactivity that can occur before thedevice locks. For example:
DevicePolicyManager mDPM; ComponentName mDeviceAdminSample; ... long timeMs = 1000L*Long.parseLong(mTimeout.getText().toString()); mDPM.setMaximumTimeToLock(mDeviceAdminSample, timeMs);
You can also programmatically tell the device to lock immediately:
DevicePolicyManager mDPM; mDPM.lockNow();
You can use the DevicePolicyManager
methodwipeData()
to reset the device to factory settings. This is usefulif the device is lost or stolen. Often the decision to wipe the device is theresult of certain conditions being met. For example, you can usesetMaximumFailedPasswordsForWipe()
to state that a device should bewiped after a specific number of failed password attempts.
You wipe data as follows:
DevicePolicyManager mDPM; mDPM.wipeData(0);
The wipeData()
method takes as its parameter a bit mask ofadditional options. Currently the value must be 0.
Beginning with Android 3.0, you can use the setStorageEncryption()
method to set a policy requiring encryption of the storage area, where supported.
For example:
DevicePolicyManager mDPM; ComponentName mDeviceAdminSample; ... mDPM.setStorageEncryption(mDeviceAdminSample, true);
See the Device Administration API sample for a completeexample of how to enable storage encryption.