Como funciona

A API do cliente oferece controle programático de dispositivos e configuração para o registro sem toque do Android. Este documento apresenta a API para provedores de gerenciamento de mobilidade empresarial (EMM) e TI corporativa desenvolvedores de aplicativos. Depois de ler este documento, você entenderá os principais recursos usados na API e como eles interagem. Se você está começando a usar o registro sem toque registro, leia o resumo android.com introdução.

Visão geral

A API do cliente ajuda as organizações que compram o registro sem toque do Android dispositivos. Seu app ou ferramenta pode ajudar os administradores de TI a fazer o seguinte:

  • Criar, editar e excluir configurações de provisionamento.
  • Aplique ou remova uma configuração de um dispositivo.
  • Selecione uma configuração padrão para todos os dispositivos adicionados ao registro sem toque daqui para frente.

Pela API, os administradores de TI também podem cancelar o registro de dispositivos no registro sem toque inscrição. Para gerenciar os usuários da organização ou aceitar os Termos de Serviço, Os administradores de TI usam o portal do registro sem toque.

Os usuários típicos dessa API podem ser:

  • Provedores de EMM adicionam suporte ao registro sem toque ao console.
  • Desenvolvedores de TI empresariais criam ferramentas para automatizar o registro sem toque tarefas.

Recursos principais

As configurações e os dispositivos são os principais recursos que você usa na API. Um as organizações também podem criar configurações e dispositivos usando o portal de inscrição.

Relação entre recursos do dispositivo e do cliente

Configuração
Os administradores de TI definem as opções de provisionamento dos dispositivos usando uma configuração. As configurações incluem políticas de EMM para dispositivos móveis e dados de contato mostrados para ajudar os usuários. Como as configurações são essenciais para a API, elas podem ser usadas em muitos métodos. Para saber mais, consulte Configurações abaixo.
Dispositivo
Um dispositivo Android compatível com o registro sem toque que foi comprado de uma organização com o revendedor. Aplicar uma configuração para incluir o dispositivo no registro sem toque inscrição. Os dispositivos têm IDs de hardware e metadados anexados. Para saber mais, consulte Dispositivos abaixo.
DPC
Uma referência somente leitura a um DPC do EMM (política do dispositivo controlador). Adicionar um DPC até uma configuração para selecionar a solução de EMM para os dispositivos. Todos os DPCs listados pela API oferecem suporte ao registro sem toque e estão disponíveis no Google Play. Para Para saber mais, consulte Dpc.

Para listar todos os métodos e recursos de API que seu aplicativo pode usar, consulte Referência da API.

Configurações

O recurso da API Configuration combina as seguinte:

  • O DPC do EMM instalado nos dispositivos.
  • Políticas de EMM aplicadas nos dispositivos.
  • Dados de contato exibidos no dispositivo para ajudar os usuários durante a configuração.

Ao usar a API, seu aplicativo pode gerenciar configurações para administradores de TI. Chame a API para buscar, criar, atualizar e excluir configurações. O exemplo abaixo mostra como crie uma nova configuração:

Java

// 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();

.NET

// 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();

Python

# 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()

Ao atualizar uma configuração usando a API de patch, lembre-se de incluir o máscara de campo, ou uma para cada campo que você não quer que sejam null. Consulte Padrão de configuração (abaixo) para um exemplo que mostra como para atualizar uma configuração com eficiência.

Excluir configurações

Não será possível excluir uma configuração se ela ainda estiver aplicada a dispositivos. Se você tentar excluir uma configuração em uso, o método da API vai retornar um HTTP 400 Bad Request de status e uma mensagem explicando quantos dispositivos usam a configuração. Ligação customers.devices.removeConfiguration para remover a configuração dos dispositivos antes de tentar novamente.

Configurações padrão

O registro sem toque funciona melhor quando uma organização define um padrão aplicada a todos os novos dispositivos comprados pela organização. Recomendamos que os administradores de TI definam uma configuração padrão, caso não haja nenhuma. O exemplo abaixo mostra como tornar uma configuração padrão definindo isDefault como true:

Java

// 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();

.NET

// 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();

Python

# 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()

Só pode haver uma configuração padrão. Ao definir uma nova configuração padrão, define o campo isDefault de uma configuração anterior como false. Talvez seja necessário atualize as instâncias Configuration armazenadas em cache para ver os valores corretos na isDefault.

Orientar os usuários do dispositivo

A configuração do registro sem toque mostra orientações personalizadas para o usuário na configuração do dispositivo para ajudar os usuários. Você precisa incluir um número de telefone e um e-mail para contato com o nome da organização que gerencia o dispositivo em um configuração do Terraform. Também recomendamos incluir uma ou duas frases no Campo customMessage para dar mais detalhes sobre o que está acontecendo com o dispositivo.

Porque o usuário não poderá ligar nem enviar e-mail usando o dispositivo configurado. formate o número de telefone e o endereço de e-mail para facilitar a visualização as informações.

Dispositivos

Os revendedores criam dispositivos quando um cliente os compra para o registro sem toque inscrição, os administradores de TI não podem criar dispositivos. Para trabalhar com dispositivos, chame métodos em o recurso da API Device. Se você precisar pesquisar para dispositivos, liste todos os dispositivos e filtre cada lote localmente em seu aplicativo. Para um exemplo, consulte Resultados paginados abaixo.

Configurar dispositivos

Aplicar uma configuração a um dispositivo faz o registro dele para o registro sem toque inscrição. Para aplicar uma configuração, chame customers.devices.applyConfiguration Depois de aplicar uma configuração, o dispositivo faz o provisionamento automaticamente na primeira inicialização ou na próxima redefinição de fábrica. O exemplo abaixo mostra como você pode aplicar configuração a um conjunto de dispositivos:

Java

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();
}

.NET

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();
}

Python

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()

Para remover a configuração de um dispositivo, chame customers.devices.removeConfiguration A alteração entra em vigor após a redefinição do dispositivo para a configuração original.

Cancelar reivindicação de dispositivos

Os administradores de TI podem cancelar a reivindicação de um dispositivo para removê-lo do registro sem toque. Um pode cancelar a reivindicação de um dispositivo que será migrado para outra conta, vendido, ou devolvidos ao revendedor. Chame o método customers.devices.unclaim para cancelar a reivindicação de um dispositivo de uma organização.

O exemplo abaixo mostra como cancelar a reivindicação do número IMEI de um dispositivo e nome do fabricante:

Java

// 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();

.NET

// 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();

Python

# 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()

Metadados do dispositivo

Um administrador de TI pode ver os metadados anexados ao dispositivo pelo revendedor. Rede de Display metadados desse dispositivo no app para ajudar os administradores de TI a reconhecer os dispositivos.

Para saber mais sobre os metadados que você pode ver, leia a página do dispositivo de metadados para revendedores.

Resultados paginados

O método da API customers.devices.list pode retornar listas muito grandes de dispositivos. Para reduzir o tamanho da resposta, esta e outra API (como customers.list) são compatíveis com resultados paginados. Com resultados paginados, seu aplicativo pode solicitar e processar listas grandes de maneira iterativa uma página por vez.

Depois de chamar o método da API, verifique se a resposta inclui um valor para nextPageToken Se nextPageToken não estiver null, seu app poderá usá-lo para buscar outra página de dispositivos chamando o novamente. Você precisa definir um limite máximo para o número de dispositivos na parâmetro pageSize. Se nextPageToken for null, o app solicitou a na última página.

O exemplo de método abaixo mostra como o app pode mostrar uma lista de dispositivos, um página por vez:

Java

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());
    }
}

.NET

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);
    }
}

Python

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'])

Primeiros passos

A seguir, leia como autorizar chamadas de API em Autorização. Se você quiser para conhecer as APIs, dê uma olhada nos guias de início rápido para Java .NET e Python. Você pode usar um colab para conferir exemplos de chamadas de API e tente chamar a API por conta própria.