Принцип работы

Клиентский API обеспечивает программный контроль устройств и настройку для автоматической регистрации Android. В этом документе API представлен поставщикам услуг управления мобильностью предприятия (EMM) и ИТ-разработчикам предприятий. Прочитав этот документ, вы должны понять основные ресурсы, используемые в API, и то, как они взаимодействуют. Если вы новичок в автоматической регистрации, прочтите краткое введение на android.com .

Обзор

Клиентский API помогает организациям, приобретающим устройства Android с автоматической регистрацией. Ваше приложение или инструмент может помочь ИТ-администраторам выполнять следующие действия:

  • Создание, редактирование и удаление конфигураций подготовки.
  • Примените или удалите конфигурацию устройства.
  • Выберите конфигурацию по умолчанию для всех устройств, добавленных в автоматическую регистрацию в дальнейшем.

С помощью API ИТ-администраторы также могут отменить регистрацию устройств из автоматической регистрации. Чтобы управлять пользователями своей организации или принимать Условия обслуживания, ИТ-администраторы используют портал автоматической регистрации.

Типичными пользователями этого API могут быть:

  • Поставщики EMM добавляют в свою консоль поддержку автоматической регистрации.
  • Корпоративные ИТ-разработчики создают инструменты для автоматизации задач автоматической регистрации.

Основные ресурсы

Конфигурации и устройства — это основные ресурсы, которые вы используете в API. Организация также может создавать конфигурации и устройства с помощью портала автоматической регистрации.

Взаимоотношения устройств и ресурсов клиента

Конфигурация
ИТ-администраторы устанавливают параметры подготовки для устройств с помощью конфигурации. Конфигурации включают мобильные политики EMM и контактную информацию, которая отображается для помощи пользователям. Конфигурации занимают центральное место в API, поэтому вы можете использовать их во многих методах. Дополнительную информацию см. в разделе «Конфигурации» ниже.
Устройство
Устройство Android с возможностью автоматической регистрации, которое организация приобрела у своего реселлера. Примените конфигурацию, чтобы включить устройство в автоматическую регистрацию. Устройства имеют идентификаторы оборудования и прикрепленные метаданные. Дополнительную информацию см. в разделе «Устройства» ниже.
ЦОД
Ссылка только для чтения на DPC EMM ( контроллер политики устройства ). Добавьте ЦОД в конфигурацию, чтобы выбрать решение EMM для устройств. Все ЦОД, перечисленные в API, поддерживают автоматическую регистрацию и доступны в Google Play. Чтобы узнать больше, см. Dpc .

Чтобы перечислить все методы и ресурсы API, которые может использовать ваше приложение, см. Справочник по API .

Конфигурации

Ресурс API Configuration сочетает в себе следующее:

  • На устройствах установлен ЦОД ЕММ.
  • На устройствах применяются политики EMM.
  • Контактная информация отображается на устройстве, чтобы помочь пользователям во время настройки.

Используя API, ваше приложение может управлять конфигурациями для ИТ-администраторов. Вызовите API для получения, создания, обновления и удаления конфигураций. В примере ниже показано, как создать новую конфигурацию:

Джава

// Add metadata to help the device user during provisioning.
Configuration configuration = new Configuration();
configuration.setConfigurationName("Sales team");
configuration.setCompanyName("XYZ Corp.");
configuration.setContactEmail("it-support@example.com");
configuration.setContactPhone("+1 (800) 555-0112");
configuration.setCustomMessage("We're setting up your phone. Call or email for help.");

// Set the DPC that zero-touch enrollment downloads and installs from Google Play.
configuration.setDpcResourcePath(dpc.getName());

// Set the JSON-formatted EMM provisioning extras that are passed to the DPC.
configuration.setDpcExtras("{"
      + "\"android.app.extra.PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED\":true,"
      + "\"android.app.extra.PROVISIONING_ADMIN_EXTRAS_BUNDLE\":{"
      + "\"default_min_password_length\":6,"
      + "\"company_name\":\"XYZ Corp\","
      + "\"management_server\":\"emm.example.com\","
      + "\"terms_url\":\"https://www.example.com/policies/terms/\","
      + "\"allowed_user_domains\":\"[\\\"example.com\\\", \\\"example.org\\\"]\""
      + "}"
      + "}");

// Create the new configuration on the server.
AndroidProvisioningPartner.Customers.Configurations.Create request =
      service.customers().configurations().create(customerAccount, configuration);
Configuration response = request.execute();

.СЕТЬ

// Add metadata to help the device user during provisioning.
Configuration configuration = new Configuration
{
    ConfigurationName = "Sales team",
    CompanyName = "XYZ Corp.",
    ContactEmail = "it-support@example.com",
    ContactPhone = "+1 (800) 555-0112",
    CustomMessage = "We're setting up your phone. Call or email for help."
};

// Set the DPC that zero-touch enrollment downloads and installs from Google Play.
configuration.DpcResourcePath = dpc.Name;

// Set the JSON-formatted EMM provisioning extras that are passed to the DPC.
configuration.DpcExtras = @"{
    ""android.app.extra.PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED"":true,
    ""android.app.extra.PROVISIONING_ADMIN_EXTRAS_BUNDLE"":{
    ""default_min_password_length"":6,
    ""company_name"":""XYZ Corp"",
    ""management_server"":""emm.example.com"",
    ""terms_url"":""https://www.example.com/policies/terms/"",
    ""allowed_user_domains"":""[\""example.com\"", \""example.org\""]""
  }
}";

// Create the new configuration on the server.
var request = service.Customers.Configurations.Create(configuration, customerAccount);
var response = request.Execute();

Питон

# Add metadata to help the device user during provisioning.
configuration = {
    'configurationName': 'Sales team',
    'companyName': 'XYZ Corp.',
    'contactEmail': 'it-support@example.com',
    'contactPhone': '+1 (800) 555-0112',
    'customMessage': 'We\'re setting up your phone. Call or email for help.'}

# Set the DPC that zero-touch enrollment installs from Google Play.
configuration['dpcResourcePath'] = dpc['name']

# Set the JSON-formatted EMM provisioning extras that are passed to the DPC.
configuration['dpcExtras'] = '''{
    "android.app.extra.PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED":true,
    "android.app.extra.PROVISIONING_ADMIN_EXTRAS_BUNDLE":{
      "default_min_password_length":6,
      "company_name":"XYZ Corp",
      "management_server":"emm.example.com",
      "terms_url":"https://www.example.com/policies/terms/",
      "allowed_user_domains":"[\\"example.com\\", \\"example.org\\"]"}
}'''

# Create the new configuration on the server.
response = service.customers().configurations().create(
    parent=customer_account, body=configuration).execute()

При обновлении конфигурации с помощью API исправлений не забудьте включить маску поля или значение для каждого поля, значение которого не должно быть null . См. «Конфигурации по умолчанию» (ниже) для примера, показывающего, как эффективно обновить конфигурацию.

Удаление конфигураций

Вы не можете удалить конфигурацию, если она все еще применяется к устройствам. Если вы попытаетесь удалить используемую конфигурацию, метод API вернет код состояния HTTP 400 Bad Request и сообщение, объясняющее, сколько устройств используют эту конфигурацию. Вызовите customers.devices.removeConfiguration , чтобы удалить конфигурацию с устройств, прежде чем повторить попытку.

Конфигурации по умолчанию

Автоматическая регистрация работает лучше всего, когда организация устанавливает конфигурацию по умолчанию, которая применяется ко всем новым устройствам, которые она приобретает. Рассмотрите возможность предложить ИТ-администраторам установить конфигурацию по умолчанию, если она еще не установлена. В примере ниже показано, как сделать существующую конфигурацию по умолчанию, установив для isDefault значение true :

Джава

// Send minimal data with the request. Just the 2 required fields.
// targetConfiguration is an existing configuration that we want to make the default.
Configuration configuration = new Configuration();
configuration.setIsDefault(true);
configuration.setConfigurationId(targetConfiguration.getConfigurationId());

// Call the API, including the FieldMask to avoid setting other fields to null.
AndroidProvisioningPartner.Customers.Configurations.Patch request = service
      .customers()
      .configurations()
      .patch(targetConfiguration.getName(), configuration);
request.setUpdateMask("isDefault");
Configuration results = request.execute();

.СЕТЬ

// Send minimal data with the request. Just the 2 required fields.
// targetConfiguration is an existing configuration that we want to make the default.
Configuration configuration = new Configuration
{
    IsDefault = true,
    ConfigurationId = targetConfiguration.ConfigurationId,
};

// Call the API, including the FieldMask to avoid setting other fields to null.
var request = service.Customers.Configurations.Patch(configuration,
                                                     targetConfiguration.Name);
request.UpdateMask = "IsDefault";
Configuration results = request.Execute();

Питон

# Send minimal data with the request. Just the 2 required fields.
# target_configuration is an existing configuration we'll make the default.
configuration = {
    'isDefault': True,
    'configurationId': target_configuration['configurationId']}

# Call the API, including the FieldMask to avoid setting other fields to null.
response = service.customers().configurations().patch(
    name=target_configuration['name'],
    body=configuration, updateMask='isDefault').execute()

Может быть только одна конфигурация по умолчанию. При создании новой конфигурации по умолчанию для поля isDefault предыдущей конфигурации устанавливается значение false . Возможно, вам придется обновить все кэшированные экземпляры Configuration , чтобы увидеть правильные значения в полях isDefault .

Руководство для пользователей устройств

Автоматическая конфигурация отображает индивидуальное руководство пользователя в мастере настройки устройства, чтобы помочь пользователям. В конфигурации необходимо указать контактный номер телефона и адрес электронной почты, а также название организации, которая управляет устройством. Мы также рекомендуем включить одно или два предложения в поле customMessage , чтобы предоставить более подробную информацию о том, что происходит с устройством пользователя.

Поскольку пользователь не сможет звонить или писать по электронной почте с устройства, которое он настраивает, отформатируйте номер телефона и адрес электронной почты, чтобы было легче просмотреть информацию.

Устройства

Реселлеры создают устройства, когда клиент приобретает их для автоматической регистрации — ИТ-администраторы не могут создавать устройства. Для работы с устройствами вызовите методы ресурса Device API. Если вам нужно выполнить поиск устройств, перечислите все устройства и отфильтруйте каждую партию локально в вашем приложении. Пример см. в разделе «Постраничные результаты» ниже.

Настройка устройств

Применение конфигурации к устройству регистрирует устройство для автоматической регистрации. Чтобы применить конфигурацию, вызовите customers.devices.applyConfiguration . После применения конфигурации устройство автоматически инициализируется при первой загрузке или следующем сбросе настроек. В примере ниже показано, как можно применить конфигурацию к коллекции устройств:

Джава

List<Device> devices = getDevicesToConfigure(service);
Configuration configurationToApply = getConfigurationToApply(service);

// Loop through the collection and apply the configuration to each device. This might
// take some time if the collection contains many devices.
for (Device device : devices) {
    System.out.println(device.getDeviceIdentifier().getImei());

    // Wrap the device ID in a DeviceReference.
    DeviceReference deviceRef = new DeviceReference();
    deviceRef.setDeviceId(device.getDeviceId());

    // Build and send the request to the API.
    CustomerApplyConfigurationRequest body = new CustomerApplyConfigurationRequest();
    body.setConfiguration(configurationToApply.getName());
    body.setDevice(deviceRef);

    AndroidProvisioningPartner.Customers.Devices.ApplyConfiguration request = service
          .customers()
          .devices()
          .applyConfiguration(customerAccount, body);
    request.execute();
}

.СЕТЬ

IList<Device> devices = GetDevicesToConfigure(service);
Configuration configurationToApply = GetConfigurationToApply(service);

// Loop through the collection and apply the configuration to each device. This might
// take some time if the collection contains many devices.
foreach (Device device in devices)
{
    Console.WriteLine(device.DeviceIdentifier.Imei);

    // Wrap the device ID in a DeviceReference.
    var deviceRef = new DeviceReference
    {
        DeviceId = device.DeviceId
    };

    // Build and send the request to the API.
    CustomerApplyConfigurationRequest body = new CustomerApplyConfigurationRequest
    {
        Configuration = configurationToApply.Name,
        Device = deviceRef
    };
    var request = service.Customers.Devices.ApplyConfiguration(body,
                                                               customerAccount);
    request.Execute();
}

Питон

devices = get_devices_to_configure(service)
configuration = get_configuration_to_apply(service)

# Loop through the collection and apply the configuration to each device.
# This might take some time if the collection contains many devices.
for device in devices:
  print(device['deviceIdentifier']['imei'])

  # Wrap the device ID in a DeviceReference.
  device_ref = {'deviceId': device['deviceId']}

  # Build and send the request to the API.
  body = {'configuration': configuration['name'], 'device': device_ref}
  service.customers().devices().applyConfiguration(
      parent=customer_account, body=body).execute()

Чтобы удалить конфигурацию с устройства, вызовите customers.devices.removeConfiguration . Изменение вступит в силу после сброса настроек устройства.

Отменить права на устройства

ИТ-администраторы могут отменить регистрацию устройства, чтобы исключить его из автоматической регистрации. ИТ-администратор может отказаться от устройства, которое он хочет перенести в другую учетную запись, продать или вернуть реселлеру. Вызовите метод customers.devices.unclaim , чтобы отменить требование устройства у организации.

В приведенном ниже примере показано, как отменить права на устройство по номеру IMEI и названию производителя:

Джава

// Wrap the hardware ID and manufacturer values in a DeviceIdentifier.
// Then wrap the DeviceIdentifier in a DeviceReference.
DeviceIdentifier identifier = new DeviceIdentifier();
identifier.setImei("123456789012347");
identifier.setManufacturer("Google");
DeviceReference reference = new DeviceReference();
reference.setDeviceIdentifier(identifier);

// Create the body of the request.
CustomerUnclaimDeviceRequest body = new CustomerUnclaimDeviceRequest();
body.setDevice(reference);

// Call the API method to unclaim the device from the organization.
service.customers().devices().unclaim(customerAccount, body).execute();

.СЕТЬ

// Wrap the hardware ID and manufacturer values in a DeviceIdentifier.
// Then wrap the DeviceIdentifier in a DeviceReference.
DeviceIdentifier identifier = new DeviceIdentifier
{
    Imei = "123456789012347",
    Manufacturer = "Google"
};
DeviceReference reference = new DeviceReference();
reference.DeviceIdentifier = identifier;

// Create the body of the request.
CustomerUnclaimDeviceRequest body = new CustomerUnclaimDeviceRequest();
body.Device = reference;

// Call the API method to unclaim the device from the organization.
service.Customers.Devices.Unclaim(body, customerAccount).Execute();

Питон

# Wrap the hardware ID and manufacturer values in a DeviceIdentifier.
# Then wrap the DeviceIdentifier in a DeviceReference.
identifier = {'imei': '123456789012347', 'manufacturer': 'Google'}
reference = {'deviceIdentifier': identifier}

# Create the body of the request.
body = {'device': reference}

# Call the API method to unclaim the device from the organization.
service.customers().devices().unclaim(
    parent=customer_account, body=body).execute()

Метаданные устройства

ИТ-администратор может видеть метаданные, прикрепленные к устройству торговым посредником. Отобразите метаданные этого устройства в своем приложении, чтобы помочь ИТ-администраторам распознавать устройства.

Чтобы узнать больше о метаданных, которые вы можете увидеть, прочтите руководство по метаданным устройства для реселлеров.

Постраничные результаты

Метод API customers.devices.list может возвращать очень большие списки устройств. Чтобы уменьшить размер ответа, этот и другие методы API (например, customers.list ) поддерживают постраничное отображение результатов. Благодаря постраничному отображению результатов ваше приложение может итеративно запрашивать и обрабатывать большие списки по одной странице за раз.

После вызова метода API проверьте, содержит ли ответ значение nextPageToken . Если nextPageToken не имеет null , ваше приложение может использовать его для получения другой страницы устройств, вызвав метод еще раз. Вам необходимо установить верхний предел количества устройств в параметре pageSize . Если nextPageToken имеет значение null , ваше приложение запросило последнюю страницу.

В приведенном ниже примере метода показано, как ваше приложение может распечатать список устройств, по одной странице за раз:

Джава

private void printDevices(AndroidProvisioningPartner service, String customerAccount,
      String pageToken) throws IOException {

    // Call the API to get a page of Devices. Send a page token from the method argument.
    // If the page token is null, the API returns the first page.
    AndroidProvisioningPartner.Customers.Devices.List request =
          service.customers().devices().list(customerAccount);
    request.setPageSize(50L);
    request.setPageToken(pageToken);
    CustomerListDevicesResponse response = request.execute();

    // Print the devices included in this page of results.
    for (Device device : response.getDevices()) {
        System.out.format("Device: %s\n", device.getName());
    }
    System.out.println("---");

    // Check to see if another page of devices is available. If yes, fetch & print the devices.
    if (response.getNextPageToken() != null) {
        this.printDevices(service, customerAccount, response.getNextPageToken());
    }
}

.СЕТЬ

private void PrintDevices(AndroidProvisioningPartnerService service, String customerAccount,
                          String pageToken)
{
    // Call the API to get a page of Devices. Send a page token from the method argument.
    // If the page token is null, the API returns the first page.
    var request = service.Customers.Devices.List(customerAccount);
    request.PageSize = 50;
    request.PageToken = pageToken;
    var response = request.Execute();

    // Print the devices included in this page of results.
    foreach (Device device in response.Devices)
    {
        Console.WriteLine("Device: {0}", device.Name);
    }
    Console.WriteLine("---");

    // Check to see if another page of devices is available. If yes, fetch and print the devices.
    if (response.NextPageToken != null)
    {
        this.PrintDevices(service, customerAccount, response.NextPageToken);
    }
}

Питон

def print_devices(service, customer_account, page_token):
  """Demonstrates how to loop through paginated lists of devices."""

  # Call the API to get a page of Devices. Send a page token from the method
  # argument. If the page token is None, the API returns the first page.
  response = service.customers().devices().list(
      parent=customer_account, pageSize=50, pageToken=page_token).execute()

  # Print the devices included in this page of results.
  for device in response['devices']:
    print('Device: {0}'.format(device['name']))
  print('---')

  # Check to see if another page of devices is available. If yes,
  # fetch and print the devices.
  if 'nextPageToken' in response:
    print_devices(service, customer_account, response['nextPageToken'])

Начать

Далее читайте, как авторизовать вызовы API в разделе Авторизация . Если вы хотите изучить API, ознакомьтесь с краткими руководствами по Java , .NET и Python . Вы можете использовать Colab , чтобы просмотреть примеры вызовов API и поэкспериментировать с вызовом API самостоятельно.