Jak to działa

Interfejs API klienta zapewnia automatyczną kontrolę nad urządzeniami i konfiguracją rejestracji typu zero-touch na Androidzie. Ten dokument stanowi wprowadzenie do interfejsu API dla dostawców usług zarządzania urządzeniami mobilnymi (EMM) i programistów IT w przedsiębiorstwach. Zapoznasz się z podstawowymi zasobami API i zapoznasz się z nimi, Jeśli po raz pierwszy korzystasz z rejestracji typu zero-touch, przeczytaj krótkie wprowadzenie na android.com.

Przegląd

Interfejs API klienta pomaga organizacjom, które kupują urządzenia do rejestracji typu zero-touch z Androidem. Aplikacja lub narzędzie może pomóc administratorom IT w:

  • Tworzenie, edytowanie i usuwanie konfiguracji obsługi administracyjnej.
  • Zastosuj konfigurację na urządzeniu lub usuń ją.
  • Wybierz domyślną konfigurację dla wszystkich urządzeń dodanych od tej pory do rejestracji typu zero-touch.

Za jego pomocą administratorzy IT mogą też wyrejestrowywać urządzenia z rejestracji typu zero-touch. Aby zarządzać użytkownikami w organizacji lub zaakceptować Warunki korzystania z usługi, administratorzy IT mogą skorzystać z portalu rejestracji typu zero-touch.

Typowi użytkownicy tego interfejsu API mogą obejmować:

  • Dostawcy usług EMM dodają w swoich konsoli obsługę rejestracji typu zero-touch.
  • Programiści IT z firmy tworzą narzędzia do automatyzacji zadań rejestracji typu zero-touch.

Zasoby podstawowe

Konfiguracje i urządzenia to podstawowe zasoby używane w interfejsie API. Organizacja może też tworzyć konfiguracje i urządzenia za pomocą portalu rejestracji typu zero-touch.

Relacja między urządzeniem a klientem

Konfiguracja
Administratorzy IT ustawiają opcje obsługi administracyjnej urządzeń przy użyciu konfiguracji. Konfiguracje obejmują zasady EMM dotyczące urządzeń mobilnych i informacje kontaktowe, które są wyświetlane użytkownikom. Konfiguracje są centralnym elementem interfejsu API, dlatego można ich używać w wielu metodach. Więcej informacji znajdziesz w sekcji Konfiguracje poniżej.
Urządzenie
urządzenie z Androidem obsługujące rejestrację typu zero-touch, które zostało kupione przez organizację od sprzedawcy. Zastosuj konfigurację, aby uwzględnić urządzenie w rejestracji typu zero-touch. Urządzenia mają identyfikatory sprzętu i dołączone metadane. Więcej informacji znajdziesz w sekcji Urządzenia poniżej.
kontroler DPC
Odniesienie tylko do odczytu do DPC (kontrolera zasad urządzeń) EMM. Dodaj DPC do konfiguracji, aby wybrać rozwiązanie EMM dla urządzeń. Wszystkie DPC wymienione przez interfejs API obsługują rejestrację typu zero-touch i są dostępne w Google Play. Więcej informacji: Dpc.

Listę wszystkich metod i zasobów interfejsu API, z których może korzystać Twoja aplikacja, znajdziesz w dokumentacji interfejsu API.

Konfiguracje

Zasób interfejsu API Configuration łączy te elementy:

  • DPC dostawcy usług EMM zainstalowany na urządzeniach.
  • Zasady EMM obowiązujące na urządzeniach.
  • Informacje kontaktowe wyświetlane na urządzeniu, aby pomóc użytkownikom podczas konfiguracji.

Za jego pomocą aplikacja może zarządzać konfiguracjami dla administratorów IT. Wywołaj ten interfejs API, aby pobierać, tworzyć, aktualizować i usuwać konfiguracje. Z przykładu poniżej dowiesz się, jak utworzyć nową konfigurację:

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

Aktualizując konfigurację za pomocą interfejsu patch API, pamiętaj o dodaniu maski pola – lub wartości każdego pola, które nie ma mieć wartości null. Przykład, który pokazuje, jak skutecznie zaktualizować konfigurację, znajdziesz poniżej w sekcji Konfiguracje domyślne.

Usuń konfiguracje

Nie możesz usunąć konfiguracji, jeśli nadal jest ona stosowana na urządzeniach. Jeśli próbujesz usunąć nieużywaną konfigurację, metoda API zwraca kod stanu HTTP 400 Bad Request i komunikat wyjaśniający, ile urządzeń korzysta z tej konfiguracji. Wywołaj customers.devices.removeConfiguration, aby usunąć konfigurację z urządzeń, zanim spróbujesz ponownie.

Konfiguracje domyślne

Rejestracja typu zero-touch działa najlepiej, gdy organizacja ustawia domyślną konfigurację, która jest stosowana na wszystkich nowych urządzeniach zakupionych przez tę organizację. W razie potrzeby poproś administratorów IT o ustawienie domyślnej konfiguracji. Poniższy przykład pokazuje, jak ustawić istniejącą konfigurację jako domyślną przez ustawienie isDefault na 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()

Może być tylko 1 konfiguracja domyślna. Utworzenie nowej konfiguracji domyślnej powoduje ustawienie w polu isDefault poprzedniej konfiguracji wartości false. Aby zobaczyć prawidłowe wartości w polach isDefault, może być konieczne odświeżenie pamięci podręcznej instancji Configuration.

Prowokowanie użytkowników urządzeń

Konfiguracja rejestracji typu zero-touch wyświetla użytkownikom dostosowane wskazówki w Kreatorze konfiguracji urządzenia, Musisz podać kontaktowy numer telefonu i adres e-mail wraz z nazwą organizacji zarządzającej urządzeniem w konfiguracji. Zalecamy też wpisanie 1 lub 2 zdań w polu customMessage, aby podać więcej informacji o tym, co dzieje się z urządzeniem użytkownika.

Użytkownik nie będzie mógł zadzwonić ani wysłać e-maila z konfigurowanego urządzenia, dlatego format numeru telefonu i adresu e-mail ułatwia przegląd informacji.

Urządzenia

Sprzedawcy tworzą urządzenia, gdy klient kupuje je do rejestracji typu zero-touch. Administratorzy IT nie mogą tworzyć urządzeń. Aby pracować z urządzeniami, wywołaj metody w zasobie interfejsu API Device. Jeśli chcesz wyszukać urządzenia, wymień wszystkie urządzenia i przefiltruj każdą grupę lokalnie w aplikacji. Przykład znajdziesz w sekcji Wyniki z podziałem na strony poniżej.

Konfigurowanie urządzeń

Zastosowanie konfiguracji na urządzeniu spowoduje zarejestrowanie go w rejestracji typu zero-touch. Aby zastosować konfigurację, wywołaj metodę customers.devices.applyConfiguration. Po zastosowaniu konfiguracji urządzenie automatycznie się konfiguruje przy pierwszym uruchomieniu lub przy następnym przywróceniu do ustawień fabrycznych. Ten przykład pokazuje, jak możesz zastosować konfigurację do zbioru urządzeń:

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

Aby usunąć konfigurację z urządzenia, wywołaj metodę customers.devices.removeConfiguration. Zmiana zostanie wprowadzona po przywróceniu ustawień fabrycznych na urządzeniu.

Usuń rezerwację urządzeń

Administratorzy IT mogą usunąć rezerwację urządzenia z rejestracji typu zero-touch. Administrator IT może wycofać rezerwację urządzenia, które chce przenieść na inne konto, sprzedać lub zwrócić sprzedawcy. Wywołaj metodę customers.devices.unclaim, aby wycofać rezerwację urządzenia w organizacji.

Poniższy przykład pokazuje, jak usunąć zgłoszenie prawa własności do urządzenia, korzystając z numeru IMEI i nazwy producenta:

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

Metadane urządzenia

Administrator IT może zobaczyć metadane dołączone do urządzenia przez sprzedawcę. Wyświetlaj metadane urządzenia w aplikacji, aby pomóc administratorom IT rozpoznawać urządzenia.

Aby dowiedzieć się więcej o metadanych, które możesz zobaczyć, przeczytaj przewodnik dla sprzedawców dotyczący metadanych urządzeń.

Wyniki podzielone na strony

Metoda interfejsu API customers.devices.list może zwracać bardzo duże listy urządzeń. Aby zmniejszyć rozmiar odpowiedzi, ta i inne metody interfejsu API (np. customers.list) obsługują wyniki z podziałem na strony. Dzięki wynikom z podziałem na strony aplikacja może iteracyjnie wysyłać żądania i przetwarzać duże listy po jednej stronie.

Po wywołaniu metody interfejsu API sprawdź, czy odpowiedź zawiera wartość nextPageToken. Jeśli nextPageToken nie jest null, aplikacja może użyć jej do pobrania innej strony urządzeń, ponownie wywołując metodę. Musisz ustawić górny limit liczby urządzeń w parametrze pageSize. Jeśli nextPageToken to null, aplikacja zażądała ostatniej strony.

W przykładowej metodzie poniżej pokazujemy, jak aplikacja może drukować listę urządzeń (po jednej stronie):

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

Rozpocznij

Następnie przeczytaj o autoryzowaniu wywołań interfejsu API w artykule Autoryzacja. Jeśli chcesz poznać interfejsy API, zapoznaj się z krótkimi przewodnikami po językach Java, .NET i Pythona. Możesz użyć colab, aby zobaczyć przykłady wywołań interfejsu API i poeksperymentować z samodzielnym wywoływaniem interfejsu API.