There are two primary user identity types for Android enterprise enrollments:
Managed Google Play accounts and Managed Google Accounts. Managed Google Play
accounts are device-centric, meaning they aren't tied to a specific user's
Google identity. In contrast, Managed Google Accounts are linked to a user's
corporate Google identity, which improves the user experience by keeping them
logged in on their devices.

Managed Google Play accounts used to be the standard. However, Google now
encourages all new development to use the improved enrollment flow, which
defaults to creating Managed Google Accounts.

While guidance for the older implementation is provided at the end of this
document for context, all new development should follow the new enrollment flow
detailed here.

## Overview

The improved device enrollment flow streamlines device setup by leveraging
several new components and changing how custom Device Policy Controllers (DPCs)
are implemented. This new approach requires custom DPC solutions to integrate
with the Android Management API (AMAPI) SDK and Android Device Policy to perform
device preparation and user enrollment functions.

The AMAPI SDK provides the necessary APIs for interacting with the Android
Device Policy on the device itself. On the server side, Enterprise Mobility
Management (EMM) solutions will use the Play EMM API to generate the enrollment
tokens required to initiate the device enrollment process.

The Android Device Policy application now assumes a central role in handling
device-side operations. [The AMAPI
SDK](https://developers.google.com/android/management/extensibility-sdk-integration) is used to manage its
installation and necessary updates on the device. Android Device Policy also
takes over the user authentication flow, handling user authentication directly
and providing the user's identity to the EMM. If Google cannot authenticate the
user for any reason, a new managed Google Play account is created and added to
the device as a fallback.

A key part of this new enrollment flow is managing the device's access to Google
services. By default, devices start in a restricted state, and the EMM plays a
crucial role in enabling access once the device is compliant.

### API Integration

Before getting started, verify that you are using the latest version of the Play
EMM API client and the AMAPI SDK.

## Enrollment implementation guide

This guide provides the necessary steps for implementing enrollment. It covers
preparing the environment, handling different enrollment methods, and managing
the device lifecycle.

### Prepare environment

Before initiating the account setup, it is necessary to prepare the device
environment. This preparation entails updating the Play Store to its latest
iteration and silently installing the Android Device Policy
(`com.google.android.apps.work.clouddpc`) onto the device. Android Device Policy
installation is essential as it houses critical components of the Account Setup
process. EMMs need not perform manual environment preparation. Instead, they
should use the
[`EnvironmentClient`](https://developers.google.com/android/management/reference/amapi/com/google/android/managementapi/environment/EnvironmentClient),
as documented at and adhere to the provided code examples.

#### Sample code

Before being able to use the
[AccountSetup](https://developers.google.com/android/management/reference/amapi/com/google/android/managementapi/accountsetup/package-summary)
API to add the work account on the device, the DPC must first verify that the
device environment is ready.

- Use
  [`EnvironmentClientFactory`](https://developers.google.com/android/management/reference/amapi/com/google/android/managementapi/environment/EnvironmentClientFactory)
  to instantiate an
  [`EnvironmentClient`](https://developers.google.com/android/management/reference/amapi/com/google/android/managementapi/environment/EnvironmentClient)
  and call
  [`prepareEnvironment`](https://developers.google.com/android/management/reference/amapi/com/google/android/managementapi/environment/EnvironmentClient#prepareEnvironment(com.google.android.managementapi.environment.model.PrepareEnvironmentRequest,android.content.ComponentName))
  or
  [`prepareEnvironmentAsync`](https://developers.google.com/android/management/reference/amapi/com/google/android/managementapi/environment/EnvironmentClient#prepareEnvironmentAsync(com.google.android.managementapi.environment.model.PrepareEnvironmentRequest,android.content.ComponentName))

      val notificationReceiverServiceName = ComponentName(context,
      NotificationReceiver::class.java)

      // An EMM should implement android.app.admin.DeviceAdminReceiver and use that
      // class to instantiate a ComponentName

      val admin = ComponentName(this, com.example.dpc.DeviceAdminReceiver::class.java)

      EnvironmentClientFactory.create(context)
          .prepareEnvironment(
              PrepareEnvironmentRequest.builder()
                  .setRoles(
                      listOf(
                          Role.builder().setRoleType(
                              Role.RoleType.DEVICE_POLICY_CONTROLLER
                          ).build()
                      )
                  )
          .setAdmin(admin)
                  .build(),
                notificationReceiverServiceName,
              )

      [Proceed with AccountSetup]

This operation could take several seconds or minutes, since applications may be
installed or updated to verify a proper working environment. Google recommends
starting this process as early as possible in the background and showing
appropriate UI while the user waits. When the operation completes, the device is
ready for the DPC to use the AccountSetup API.

> [!NOTE]
> **Note:** The `AccountSetupClient` can be created before the environment is ready, but cannot be used.

### Enrollment flow

EMMs must discontinue using `users.generateAuthenticationToken()` and
`users.insert()` for all devices. Instead, EMMs must call the [on-device
API](https://developers.google.com/android/management/reference/amapi/com/google/android/managementapi/accountsetup/AccountSetupClient#launchAuthenticationActivity(com.google.android.managementapi.accountsetup.model.LaunchAuthenticationActivityRequest))
to perform end-user authentication. The new API will return the **`userId`** and
**`email`** to the DPC. If Google is not able to authenticate the user, a
Managed Google Play Account will be created and added to the device. In this
case, Google will return the **`userId`** of that account.

Google now introduces the use of enrollment tokens, which must be passed to the
authentication API. EMMs determine when and how to create the token, and it can
be part of an existing enrollment payload (e.g., a QR code or Zero-touch
configuration).
>
> #### Exemption for existing enrollment tokens
>
> Some customers use enrollment tokens with long expiration dates to perform
> repeated enrollments. To make sure these existing workflows aren't
> interrupted, any tokens created BEFORE the "Authenticate using Google"
> requirement was first enabled are exempt from the new login prompts.
> These older tokens will continue to work as they did
> before, allowing users to enroll devices without undergoing the Google
> authentication process.
> However, any tokens created AFTER the Google
> authentication requirement was first turned on will follow the new
> authentication rules. This means that devices using these newer tokens will
> require users to authenticate according to the settings chosen by the IT
> admin.

Google recommends creating the token on demand and replacing the
existing API for Managed Google Play Accounts with the new API to minimize
the change.
![Typical DPC integration with previous APIs](https://developers.google.com/static/android/work/play/emm-api/images/implementation-guide-1.png) **Figure 1.** Typical DPC integration with previous APIs ![Example DPC integration with new APIs for userless devices](https://developers.google.com/static/android/work/play/emm-api/images/implementation-guide-2.png) **Figure 2.** Example DPC integration with new APIs for userless devices ![Example DPC integration with new APIs for user devices](https://developers.google.com/static/android/work/play/emm-api/images/implementation-guide-3.png) **Figure 3.** Example DPC integration with new APIs for user devices

The improved custom DPC enrollment flow involves the following steps:
> **Important Initial Device State:** When enrolling a device with a custom DPC,
> the Google Account added to the device begins in a **disabled** state. This
> means access to Google services, including Google Play, is initially
> restricted.
>
> This default "disabled" status and the subsequent requirement
> for the EMM to mark the device as compliant (e.g., by calling
> Devices.SetState) are specifically applicable under these conditions:
>
> 1. The organization has verified ownership of their domain with Google.
> 2. The IT admin has explicitly enabled third-party Android mobile management for the user's specific Organizational Unit (OU) within the Google Admin console.

1. **Create Enrollment Token:** The EMM creates an enrollment token using the Play EMM API.
2. **Prepare Environment:** The custom DPC uses the [Prepare Environment flow](https://developers.google.com/android/work/play/emm-api/implement-user-accounts#prepare-environment) to verify the device is ready for enrollment.
3. **Initiate Enrollment:** The custom DPC invokes the [`startAccountSetup`](https://developers.google.com/android/management/reference/amapi/com/google/android/managementapi/accountsetup/model/StartAccountSetupRequest) API in the AMAPI SDK, passing the enrollment token. Note: The DPC must be either device owner or profile owner before calling this API.
4. **Launch Google authentication activity:** If required, the custom DPC invokes the [`launchAuthenticationActivity`](https://developers.google.com/android/management/reference/amapi/com/google/android/managementapi/accountsetup/model/LaunchAuthenticationActivityRequest) API in the AMAPI SDK, passing the [`AccountSetupAttempt`](https://developers.google.com/android/management/reference/amapi/com/google/android/managementapi/accountsetup/model/LaunchAuthenticationActivityRequest#getAccountSetupAttempt()). This starts a Google authentication activity, returning the user to the custom DPC upon successful authentication. The user can also skip this process. In this case, a Managed Google Play account will be added to the device. This option can be configured using `googleAuthenticationOptions`.
5. **Finalize Enrollment:** The AMAPI SDK notifies the custom DPC of the enrollment result.
6. **Enable Google services:** Once the custom DPC has fully provisioned the device and confirmed it complies with all enterprise policies, the EMM server **must** call [`Devices.setState()`](https://developers.google.com/android/work/play/emm-api/v1/devices/setState) with the `accountState` parameter set to `"enabled"`.

- **Why this is essential:** This API call marks the device as compliant.
- **Consequence of not calling:** Without this `Devices.setState(setStateRequest)` call, the account remains in the "disabled" state. The user will be unable to access Google Play (to install or update apps) and other Google services that require account authentication.

## Managing Device State and Service Access

After the initial enrollment, the EMM is responsible for maintaining the
device's access to Google services based on its compliance status.

### Handling Service Disruptions: BAD_DEVICE_MANAGEMENT

If a device's access to Google services is blocked, Google Play services
(GMSCore) will broadcast an Intent with the action:
`com.google.android.gms.auth.BAD_DEVICE_MANAGEMENT`. This can happen for
several reasons:

- The EMM never called Devices.setState("enabled") after the initial device enrollment.
- The device no longer complies with EMM policies, and the EMM has not yet re-enabled it.
- The EMM explicitly set the device state to "disabled" by calling Devices.setState() with accountState set to "disabled". This might be due to security concerns, administrative actions, or other reasons.

This Intent includes a status code, such as `"ThirdPartyDeviceManagementRequired"`.

**Custom DPCs MUST implement a `BroadcastReceiver` to listen for this `BAD_DEVICE_MANAGEMENT` Intent.**

Upon receiving this broadcast, the DPC should:

1. **Re-assess Compliance:** Check if the device meets all the policies set by the EMM.
2. **Take Action:**
   - **If Compliant:** The DPC should notify the EMM server. The EMM server should then call [`Devices.setState()`](https://developers.google.com/android/work/play/emm-api/v1/devices/setState) with `accountState` set to `"enabled"` for the specific user ID and device ID to attempt to restore service access.
   - **If Not Compliant:** Once the issues are resolved, and the device is compliant, the EMM should call `Devices.setState()`.

This mechanism ensures that there's a way to detect and recover from situations
where a device loses access to Google services.

### Enterprise Takeover Considerations

Changes in the organization's account type (e.g., from
`ManagedGoogleDomainType.TYPE_TEAM` to `ManagedGoogleDomainType.TYPE_DOMAIN`)
can occur. While this process doesn't typically break the EMM binding, it can
sometimes disrupt Google service access on devices.

EMMs should be aware that if users report service access issues after a known
takeover event, even if the device appears compliant with EMM policies, a call
to `Devices.setState()` might be necessary to re-synchronize the device's state
with Google's backends under the new customer structure. Proactive calls for all
devices post-takeover are generally not required, but it's a key tool for
resolving access problems.

### Account Setup - sample code

1. To initiate an account setup attempt, the calling app can use
   [`AccountSetupClient`](https://developers.google.com/android/management/reference/amapi/com/google/android/managementapi/accountsetup/AccountSetupClient)
   and call either the
   [`startAccountSetup()`](https://developers.google.com/android/management/reference/amapi/com/google/android/managementapi/accountsetup/AccountSetupClient#startAccountSetup(com.google.android.managementapi.accountsetup.model.StartAccountSetupRequest))
   or
   [`startAccountSetupFuture()`](https://developers.google.com/android/management/reference/amapi/com/google/android/managementapi/accountsetup/AccountSetupClient#startAccountSetupFuture(com.google.android.managementapi.accountsetup.model.StartAccountSetupRequest))
   method. For an example implementation, see the following code sample:

       // Create AccountSetupClient
       val client = AccountSetupClientFactory.create(
           this,
           activityResultRegistry
       )
       lifecycle.addObserver(client.lifecycleObserver)

       // Create adminComponent
       val notificationReceiver = ComponentName(this, AccountSetupNotificationReceiver::class.java)
       // Helper method to get enrollment token created with Play EMM API
       val enrollmentToken = getEnrollmentToken()
       val request =
           StartAccountSetupRequest.builder()
               .setEnrollmentToken(enteredText)
               .setNotificationReceiverServiceComponentName(notificationReceiver)
               .setAdminComponentName(
                   ComponentName(this, com.example.dpc.DeviceAdminReceiver::class.java))
               .build()
       try {
           val accountSetupAttempt = client.startAccountSetup(request)
           // handle attempt
       } catch (e: Exception) {
           // handle exception
       }

2. Implement
   [`AccountSetupListener`](https://developers.google.com/android/management/reference/amapi/com/google/android/managementapi/accountsetup/AccountSetupListener)
   interface and provide an implementation for how to handle the received
   status updates.

3. Extend
   [`NotificationReceiverService`](https://developers.google.com/android/management/reference/amapi/com/google/android/managementapi/notification/NotificationReceiverService)
   and provide the
   [`AccountSetupListener`](https://developers.google.com/android/management/reference/amapi/com/google/android/managementapi/accountsetup/AccountSetupListener)
   instance created in step 2 by overriding `getAccountSetupListener()`.

       // Handles account setup changes
       class AccountSetupNotificationReceiver :
             NotificationReceiverService(),
             AccountSetupListener {

           override fun getAccountSetupListener(): AccountSetupListener = this

           override fun onAccountSetupChanged(accountSetupAttempt:
         AccountSetupAttempt) {

               when (accountSetupAttempt.state.kind) {
                   StateCase.ADDED_ACCOUNT -> {
                       val enterpriseAccount = state.addedAccount()
                       val userId = enterpriseAccount.userId
                       val deviceId = enterpriseAccount.deviceId
                       // Handle account added state.

                       // IMPORTANT: The device/account is now added but *DISABLED*
                       // for Google services. Your EMM backend MUST be notified to
                       // perform policy compliance checks and then call Devices.setState()
                       // to activate Google Play and other services.

                   }
                   StateCase.AUTHENTICATION_ACTIVITY_LAUNCH_REQUIRED -> {
                       val request = LaunchAuthenticationActivityRequest.builder()
                   .setAccountSetupAttempt(accountSetupAttempt)
                   .build();
                       // Send the attempt to the foreground activity to call:
                       accountSetupClient.launchAuthenticationActivity(request)
                   }
                   StateCase.ACCOUNT_SETUP_ERROR -> {
                       // Handle error state.
                       val failureReason = state.accountSetupError().failureReason
                   }
                   else -> {
                       // Handle unknown account setup attempt state.
                   }
               }
           }
       }

4. Add the extended
   [`NotificationReceiverService`](https://developers.google.com/android/management/reference/amapi/com/google/android/managementapi/notification/NotificationReceiverService)
   class to your `AndroidManifest.xml` and verify it is exported.

         <application>
           <service
               android:name = ".accountsetup.AccountSetupNotificationReceiver"
               android:exported = "true" />
         </application>

   If your app targets SDK 30 or later, then a queries element is needed in the
   `AndroidManifest.xml` to specify that it will interact with ADP.

         <queries>
           <package android:name="com.google.android.apps.work.clouddpc" />
         </queries>

## Testing guidance

This section provides a set of guidelines and best practices for testing your
implementation.

### Test `PrepareEnvironment`

1. **Get Device's Current State:** The EMM runs

       adb shell dumpsys package com.google.android.apps.work.clouddpc | grep versionName

   to get the version of the Android Device Policy present on the device. If the
   Android Device Policy is not installed, an empty output is expected.
2. **Integrate PrepareEnvironment:** The custom DPC invokes [`prepareEnvironment`](https://developers.google.com/android/management/reference/amapi/com/google/android/managementapi/environment/model/PrepareEnvironmentRequest)
   API in the AMAPI SDK, passing the correct request.

3. **Await PrepareEnvironment result:** The custom DPC waits for the [`prepareEnvironment`](https://developers.google.com/android/management/reference/amapi/com/google/android/managementapi/environment/model/PrepareEnvironmentRequest)
   to complete.

4. **Confirm PrepareEnvironment success:** On completion, EMM runs again

       adb shell dumpsys package com.google.android.apps.work.clouddpc | grep versionName

   This time the Android Device Policy version should be higher than in step 1.

### Test Google Account authentication

1. **Create test enterprise:** The EMM creates a test domain Google enterprise linked to a test EMM, with [`enterprises.generateSignupUrl`](https://developers.google.com/android/work/play/emm-api/v1/enterprises/generateSignupUrl).
2. **Enable Google authentication:** The EMM enables Google authentication for the test enterprise following [these instructions](https://support.google.com/work/android/answer/9415508#zippy=%2Cemm-setup%2Crecommended-step-enable-authenticate-using-google) in the Google Admin console.
3. **Create Enrollment Token:** The EMM creates an enrollment token using the Play EMM API with type *userDevice*.
4. **Initiate Enrollment:** The custom DPC invokes the [`startAccountSetup`](https://developers.google.com/android/management/reference/amapi/com/google/android/managementapi/accountsetup/model/StartAccountSetupRequest) API in the AMAPI SDK, passing the enrollment token.
5. **Launch activity required:** The AMAPI SDK notifies the custom DPC that an activity must be launched to authenticate the user.
6. **Authenticate the user:** The custom DPC invokes [`launchAuthenticationActivity`](https://developers.google.com/android/management/reference/amapi/com/google/android/managementapi/accountsetup/model/LaunchAuthenticationActivityRequest) to start the activity. The user authenticates with a Managed Google Account (part of the enterprise created in step 1).
7. **Finalize Enrollment:** The AMAPI SDK notifies the custom DPC of the enrollment result.

### Test skipping Google authentication

We will use the previously described setup.

This time, in step 7, the user presses *Skip* instead of authenticating with
their Google Account. The enrollment completes successfully, with a service
account on the device (i.e. the
[`AuthenticationType`](https://developers.google.com/android/management/reference/amapi/com/google/android/managementapi/accountsetup/model/AccountSetupAttempt.EnterpriseAccount.AuthenticationType#ANONYMOUS)
is Anonymous).

### Test userless devices

The improved custom DPC enrollment flow utilizes the followeing steps, when
Google authentication is disabled:

1. **Create a test enterprise:** This can be the same enterprise as created previously.
2. **Create Enrollment Token:** The EMM creates an enrollmenttoken using the Play EMM API with type *userlessDevice*.
3. **Initiate Enrollment:** The custom DPC invokes the [`startAccountSetup`](https://developers.google.com/android/management/reference/amapi/com/google/android/managementapi/accountsetup/model/StartAccountSetupRequest) API in the AMAPI SDK, passing the enrollment token.
4. **Finalize Enrollment:** The AMAPI SDK notifies the custom DPC of the enrollment result.

## Managed Google Play Accounts

> [!NOTE]
> **Important:** The development guidance in this section has been replaced by the new enrollment flow detailed at the beginning of this guide.  
> Direct provisioning of Managed Google Play accounts is now discouraged except as part of an enrollment token mapped to a userless enrollment.

#### User account

Provides a single user access to managed Google Play from all their
devices. You must provision user accounts for your users. They don't have
the credentials to add managed Google Play Accounts themselves.

To create a user account, call [`Users.insert`](https://developers.google.com/android/work/play/emm-api/v1/users/insert).
Set the account type to `userType`, and set an
`accountIdentifier`, which uniquely references the user within
the enterprise.

**Best practice:** Don't use the same account on more than
10 devices.

#### Device account

Provides access to managed Google Play from a single device. If an
authentication token has been issued for a device account, a new request
for an authentication token for that device account deactivates the
previous token. Each device should have its own separate licenses for
apps.

To create a device account, call [`Users.insert`](https://developers.google.com/android/work/play/emm-api/v1/users/insert)
and set the account type to `deviceType`.
![](https://developers.google.com/static/android/work/play/emm-api/images/mgpa-scenario.png)

You create and maintain a mapping between the user or device identities
and the corresponding managed Google Play Accounts, and you manage the
accounts through their lifecycle. The organization doesn't need any direct
control over these managed Google Play Accounts, as the accounts exist
purely for application management.

### Create a managed Google Play user account

1. A user signs in to your DPC using corporate credentials.
2. The DPC requests details about the user from the EMM server or console.
3. Assuming the user is unknown to your system:
   1. Submit request for new managed Google Play Account by calling [`Users.insert`](https://developers.google.com/android/work/play/emm-api/v1/users/insert) with values for new `accountIdentifier`, `displayName` , and `accountType`.
      - Your system must create the `accountIdentifier`. The account identifier must be a unique value across your system. Don't use PII for the account identifier.
      - The `displayName` is shown in the account switcher of the Google Play Store and should have some meaning to the user (but not PII about the user). For example, the name could include the organization name or a generic name related to the EMM.
      - Set the `accountType` to `userAccount` or `deviceAccount`. A `userAccount` is specific to a single device. The `accountType` specified can be `deviceType` or `userType`.
      - Set `managementType` to `emmManaged`.
   2. Google Play processes the request, creates the account, and returns a `userId`.
   3. Store the mapping between the `accountIdentifier` and the `userId` in your datastore.
   4. Call [`Users.generateAuthenticationToken`](https://developers.google.com/android/work/play/emm-api/v1/users/generateAuthenticationToken) with the `userId` and the `enterpriseId`. Google Play returns an authentication token that can be used once, and which must be used within a few minutes.
   5. Securely forward the authentication token to your DPC.
4. The DPC provisions the work profile and adds the account to the work profile or device.
5. The user can access managed Google Play within the work profile or device.

> [!NOTE]
> **Note:** The **userId** is specific to an EMM and cannot be used with another EMM. If an enterprise unenrolls from one EMM and enrolls with another, the **userId** won't be recognized by the new EMM. EMMs can use [`Users.delete`](https://developers.google.com/android/work/play/emm-api/v1/users/delete) to delete EMM-managed users.

### Admin accounts

When an admin [creates
an enterprise with managed Google Play Accounts](https://developers.google.com/android/work/play/emm-api/create-enterprise#managed_google_play_accounts_enterprise_enrollment), the Google Account they
use can't be a G Suite account. The account they use becomes an owner for the
enterprise, and the owner can add more owners and admins in the managed Google
Play console.

Both [`Enterprises.get`](https://developers.google.com/android/work/play/emm-api/v1/enterprises/get) and [`Enterprises.completeSignup`](https://developers.google.com/android/work/play/emm-api/v1/enterprises/completeSignup)
return a list of admin email addresses that are associated with an enterprise
(enterprises with managed Google Play Accounts only).

### Manage account life cycles

In a managed Google Play Accounts deployment, you're responsible for user
and device account life cycles, which means you create, update, and delete
these accounts.

You create the accounts during device provisioning, a process that involves
your DPC app and your EMM console. For instructions, see the [managed Google Play
Accounts](https://developers.google.com/android/work/play/emm-api/prov-devices#managed_google_play_accounts_method) method.

> [!NOTE]
> **Important privacy note:** When you create a managed Google Play Account , use an anonymous identifier, one that doesn't reveal actual user identity to Google. For example:
>
> - Set **accountIdentifier** to an existing internal ID or a new mapping that you create. Don't use the user's email address or name.
> - Leave the **displayName** property unset, or set it to something generic for you or the organization, for example "ACME, Inc."

To change an account's information, call [`Users.update`](https://developers.google.com/android/work/play/emm-api/v1/users/update).

To delete an account, call [`Users.delete`](https://developers.google.com/android/work/play/emm-api/v1/users/delete)

Admins can't delete individual accounts, but they can delete an enterprise
with managed Google Play Accounts. When they do this, the device and user
accounts associated with the enterprise are eventually deleted, as described in [Unenroll, re-enroll, delete](https://developers.google.com/android/work/play/emm-api/create-enterprise#unenroll_re-enroll_or_delete_an_enterprise_binding).

### Account expiration

Occasionally, accounts or their tokens expire. This can happen for several
reasons:

- The [authentication token](https://developers.google.com/android/work/play/emm-api/v1/users/generateAuthenticationToken) used to add the account to the device has expired.
- The account or enterprise has been [deleted](https://developers.google.com/android/work/play/emm-api/create-enterprise#unenroll_re-enroll_or_delete_an_enterprise).
- For device accounts, the account has been added to a new device and is therefore disabled on the old one.
- Automatic abuse checks have been triggered.

Additionally, a device's information may be deleted due to a batch cleanup
process if it remains offline for more than 270 days.

In most cases (unless the EMM is intentionally moving a device account to a
new device), the best practice is to use the Play EMM API to request a new token
from the EMM server, note the state of the account and enterprise and any
returned errors, and then take appropriate action on the device. For example,
renew the token, or if the error isn't recoverable, reset or unenroll the
device.

To properly renew the token you should:

1. Call [`users.generateAuthenticationToken`](https://developers.google.com/android/work/play/emm-api/v1/users/generateAuthenticationToken).
2. If the call is successful, remove the existing account and add the new account using the DPC support library.
3. If the call is unsuccessful, remove the account from the device and create a new user using [`users.insert`](https://developers.google.com/android/work/play/emm-api/v1/users/insert), generate an authentication token and add the account to the device.

[Google Play
services](https://developers.google.com/android/guides/overview) version 9.0.00 notifies your DPC that the account has expired
using the broadcast action:

1. When the managed Google Play Account is invalidated on a device, the DPC receives a broadcast with the following action:
2. `com.google.android.gms.auth.ACCOUNT_REAUTH_REQUIRED`
3. The broadcast intent contains `Parcelable` extra with name `account`, which is the [`Account`](https://developer.android.com/reference/android/accounts/Account.html) object of the invalidated account.
4. The DPC checks [`Account#name`](https://developer.android.com/reference/android/accounts/Account.html#name) with the EMM server to identify the invalidated account.
5. The DPC either requests new credentials or a new account, following the same flow used to [provision the device](https://developers.google.com/android/work/play/emm-api/prov-devices#managed_google_play_accounts_method) initially.