A API Customer oferece controle programático de dispositivos e configuração para o registro sem toque do Android. Este documento apresenta a API a provedores de gerenciamento de mobilidade empresarial (EMM) e desenvolvedores de TI empresariais. Depois de ler este documento, você vai entender os principais recursos usados na API e como eles interagem. Se você não conhece o registro sem toque, leia a breve introdução do android.com.
Visão geral
A API Customer ajuda as organizações que compram dispositivos Android com registro sem toque. 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 a partir de agora.
Por meio da API, os administradores de TI também podem cancelar a inscrição de dispositivos no registro sem toque. 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 comuns dessa API podem ser:
- Provedores de EMM adicionando suporte ao registro sem toque ao console deles.
- Desenvolvedores de TI empresariais que criam ferramentas para automatizar tarefas de registro sem toque.
Recursos principais
As configurações e os dispositivos são os principais recursos que você usa na API. Uma organização também pode criar configurações e dispositivos usando o portal de registro sem toque.
- Configuração
- Os administradores de TI definem opções de provisionamento para dispositivos usando uma configuração. As configurações incluem políticas de EMM para dispositivos móveis e dados de contato exibidos para ajudar os usuários. As configurações são essenciais para a API, portanto, elas são usadas em muitos métodos. Para saber mais, consulte Configurações abaixo.
- Dispositivo
- Um dispositivo Android com registro de registro sem toque que uma organização comprou do revendedor. Aplique uma configuração para incluir o dispositivo no registro sem toque. Os dispositivos têm IDs de hardware e metadados anexados. Para saber mais, consulte Dispositivos abaixo.
- DPC
- Uma referência somente leitura ao DPC de um EMM (controlador de política do dispositivo). Adicione um DPC
a uma configuração para selecionar a solução de EMM para dispositivos. Todos os DPCs listados
pela API são compatíveis com o registro sem toque e estão disponíveis no Google Play. Para
saber mais, consulte
Dpc
.
Para listar todos os métodos e recursos da API que seu app pode usar, consulte a Referência da API.
Configurações
O recurso da API Configuration
combina o 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.
Usando a API, seu app pode gerenciar configurações para administradores de TI. Chame a API para buscar, criar, atualizar e excluir configurações. O exemplo abaixo mostra como criar 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 patch, inclua a
máscara de campo, ou um
valor para cada campo que você não quer que seja null
. Consulte Configurações
padrão (abaixo) para ver um exemplo que mostra como
atualizar uma configuração com eficiência.
Excluir configurações
Não será possível excluir uma configuração se ela ainda for aplicada a dispositivos. Se você tentar
excluir uma configuração em uso, o método da API retornará um código de status HTTP
400 Bad Request
e uma mensagem explicando quantos dispositivos usam a configuração.
Chame
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 uma configuração
padrão aplicada a todos os novos dispositivos que ela comprar.
Peça aos administradores de TI que definam uma configuração padrão, caso ela não tenha sido definida.
O exemplo abaixo mostra como definir uma configuração atual como 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 fazer uma nova configuração padrão,
você define o campo isDefault
de uma configuração anterior como false
. Talvez seja necessário
atualizar as instâncias de Configuration
em cache para conferir os valores corretos nos
campos isDefault
.
Guiar usuários do dispositivo
A configuração sem toque exibe orientações personalizadas para os usuários no assistente
de configuração do dispositivo. É necessário incluir um número de telefone e um endereço de
e-mail de contato com o nome da organização que gerencia o dispositivo em uma
configuração. Também recomendamos incluir uma ou duas frases no campo
customMessage
para dar mais detalhes sobre o que está acontecendo com o dispositivo
de um usuário.
Como o usuário não poderá ligar ou enviar e-mails do dispositivo que está configurando, formate o número de telefone e o endereço de e-mail para facilitar a visualização das informações.
Dispositivos
Os revendedores criam dispositivos quando um cliente os compra para o registro sem toque.
Os administradores de TI não podem criar dispositivos. Para trabalhar com dispositivos, chame métodos no
recurso da API Device
. Se precisar pesquisar
dispositivos, liste todos os dispositivos e filtre cada lote localmente no app. Para
ver um exemplo, consulte os Resultados paginados abaixo.
Configurar dispositivos
Quando você aplica uma configuração a um dispositivo, ele é registrado no registro sem toque. Para aplicar uma configuração, chame
customers.devices.applyConfiguration
.
Depois de aplicar uma configuração, o dispositivo é provisionado automaticamente na
primeira inicialização ou na próxima redefinição para a configuração original. O exemplo abaixo mostra como aplicar uma configuração a uma coleção 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 mudança entra em vigor após a redefinição de fábrica do dispositivo.
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 administrador
de TI pode cancelar a reivindicação de um dispositivo que quer migrar para outra conta, vender
ou devolver ao revendedor. Chame o método
customers.devices.unclaim
para cancelar a reivindicação de um dispositivo
em uma organização.
O exemplo abaixo mostra como cancelar a reivindicação de um dispositivo usando um número IMEI e o 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
O administrador de TI pode ver os metadados anexados ao dispositivo pelo revendedor. Exiba metadados de dispositivos no seu app para ajudar os administradores de TI a reconhecer dispositivos.
Para saber mais sobre os metadados que você pode ver, leia o guia Metadados do dispositivo 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, esse e outros métodos
de API (como customers.list
) são compatíveis com resultados paginados. Com
os resultados paginados, seu aplicativo pode solicitar e processar iterativamente listas grandes
uma página por vez.
Depois de chamar o método de API, verifique se a resposta inclui um valor para
nextPageToken
. Se nextPageToken
não for
null
, o app vai poder usá-lo para buscar outra página de dispositivos chamando o
método novamente. É necessário definir um limite máximo para o número de dispositivos no parâmetro pageSize
. Se nextPageToken
for null
, significa que o app solicitou a
última página.
O exemplo de método abaixo mostra como o app pode imprimir uma lista de dispositivos, uma 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'])
Começar
Em seguida, leia como autorizar chamadas de API em Autorização. Se você quiser explorar as APIs, consulte os guias de início rápido para Java, .NET e Python.