Giriş
El değmeden kayıt API'si, cihaz bayilerinin entegrasyonlarını otomatikleştirmelerine yardımcı olur. Kuruluşunuzun satış araçları, el değmeden kayıt özelliğini oluşturarak kullanıcılarınızın ve müşterilerinizin daha verimli olmasını sağlar. Kullanıcılarınıza yardımcı olmak için API'yi kullanın:
- Satın alınan cihazları müşterinin el değmeden kayıt hesabına atayın.
- Müşterinizin el değmeden kayıt hesabını oluşturun.
- Kuruluşunuzun telefon ve sipariş meta verilerini cihazlara ekleyin.
- Müşterilerinize atanan cihazlar hakkında raporlar oluşturun.
Bu belgede API tanıtılmakta ve kalıplar açıklanmaktadır. API'yi kendiniz keşfetmek istiyorsanız Java, .NET veya Python hızlı başlangıç kılavuzunu deneyin.
API kavramları
Müşteriler ve cihazlar, API'de kullandığınız temel kaynaklardır. Müşteri oluşturmak için create
numaralı telefonu arayın. Hak talebi API yöntemlerini kullanarak cihaz oluşturabilirsiniz (aşağıya bakın). Kuruluşunuz el değmeden kayıt portalını kullanarak müşteriler ve cihazlar da oluşturabilir.
- Müşteri
- Kuruluşunuzun cihaz sattığı şirketler. Müşterilere
name
veID
verilir. Cihazlarını talep etmek veya bulmak için bir müşteriyi kullanın. Daha fazla bilgi içinCustomer
sayfasını inceleyin. - Cihaz
- Kuruluşunuzun bir müşteriye sattığı el değmeden kayıt özellikli Android veya ChromeOS cihaz. Cihazların donanım kimlikleri, meta verileri ve müşteri talepleri vardır. Cihazlar, API'nin merkezinde yer aldığı için bunları hemen hemen tüm yöntemlerde kullanırsınız. Daha fazla bilgi için
Device
sayfasına bakın. - DeviceIdentifier
- Üretilmiş bir cihazı tanımlamak için IMEI veya MEID gibi donanım kimliklerini içerir. Bulmak, güncellemek veya talep etmek istediğiniz cihazı hedeflemek için
DeviceIdentifier
kullanın. Daha fazla bilgi için Tanımlayıcılar bölümünü okuyun. - DeviceMetadata
- Cihaz için meta veri anahtar/değer çiftlerini depolar. Kuruluşunuzun meta verilerini depolamak için
DeviceMetadata
kullanın. Daha fazla bilgi edinmek için Cihaz meta verileri bölümünü okuyun.
Uygulamanızın kullanabileceği tüm API yöntemlerini ve kaynakları listelemek için API Referansı'nı inceleyin.
Müşteri oluşturma
Android cihazlarda, müşterisi adına müşteri hesabı oluşturmak bayinin sorumluluğundadır. Müşteri, el değmeden kayıt portalına erişmek için bu hesabı kullanarak cihazlarının temel hazırlık ayarlarını yapılandırabilir. Bu işlem, temel hazırlık ayarlarını yapılandırmak için kullanacakları bir Google Workspace hesabına sahip ChromeOS cihazlar için gerekli değildir.
El değmeden kayıt için müşteri hesapları oluşturmak istiyorsanız create
API yöntemini çağırabilirsiniz. Müşterileriniz şirket adını el değmeden kayıt portallarında gördüğünden, uygulamanızın kullanıcısı bu adın doğru olduğunu onaylamalıdır. Müşteriyi oluşturduktan sonra bu müşterinin adını düzenleyemezsiniz.
Hesabın sahibi olmak için, Google Hesabı ile ilişkilendirilmiş en az bir şirket e-posta adresini eklemeniz gerekir. Kişisel Gmail hesaplarını API ile kullanamazsınız. Müşterinin hesabı ilişkilendirme konusunda yardıma ihtiyacı varsa Google Hesabı İlişkilendirme bölümündeki talimatları gönderin.
API'yi çağırarak oluşturduğunuz bir müşteri, çalışanlarının portal erişimini yönetir. API'yi kullanarak müşterilerinizin kullanıcılarını düzenleyemezsiniz. Aşağıdaki snippet'te nasıl müşteri oluşturabileceğiniz gösterilmektedir:
Java
// Provide the customer data as a Company type. // The API requires a name and owners. Company customer = new Company(); customer.setCompanyName("XYZ Corp"); customer.setOwnerEmails(Arrays.asList("liz@example.com", "darcy@example.com")); customer.setAdminEmails(Collections.singletonList("jane@example.com")); // Use our reseller ID for the parent resource name. String parentResource = String.format("partners/%d", PARTNER_ID); // Call the API to create the customer using the values in the company object. CreateCustomerRequest body = new CreateCustomerRequest(); body.setCustomer(customer); Company response = service.partners().customers().create(parentResource, body).execute();
.NET
// Provide the customer data as a Company type. // The API requires a name and owners. var customer = new Company { CompanyName = "XYZ Corp", OwnerEmails = new String[] { "liz@example.com", "darcy@example.com" }, AdminEmails = new String[] { "jane@example.com" } }; // Use our reseller ID for the parent resource name. var parentResource = String.Format("partners/{0}", PartnerId); // Call the API to create the customer using the values in the company object. var body = new CreateCustomerRequest { Customer = customer }; var request = service.Partners.Customers.Create(body, parentResource); var response = request.Execute();
Python
# Provide the customer data as a Company type. The API requires # a name and at least one owner. company = {'companyName':'XYZ Corp', \ 'ownerEmails':['liz@example.com', 'darcy@example.com'], \ 'adminEmails':['jane@example.com']} # Use our reseller ID for the parent resource name. parent_resource = 'partners/{0}'.format(PARTNER_ID) # Call the API to create the customer using the values in the company object. response = service.partners().customers().create(parent=parent_resource, body={'customer':company}).execute()
Müşterinizin çalışanları için sahip ve yönetici rolleri hakkında daha fazla bilgi edinmek için Portal kullanıcıları bölümünü okuyun.
Müşteriler için cihaz talep edin
Müşterileriniz cihaz satın aldıktan sonra hesaplarında bu cihazların temel hazırlık ayarlarını yapılandırmak isteyecektir. Bir cihaz talep edildiğinde, cihaz el değmeden kayıt sürecine eklenir ve müşteriye temel hazırlık ayarlarını yapılandırabilir.
Bir cihazın temel hazırlık kaydında el değmeden kayıt için bir bölüm bulunur. Cihazı, kaydın el değmeden kayıt bölümünde bir müşteri için talep ederek atarsınız. Bağımsız değişken olarak müşteriyle partners.devices.claim
veya partners.devices.claimAsync
yöntemlerini çağırın. sectionType
için her zaman SECTION_TYPE_ZERO_TOUCH
değerini sağlayın.
Aynı cihazı farklı bir müşteri için talep etmeden önce müşterinin cihazıyla ilgili hak talebini iptal etmeniz (aşağıya bakın) gerekir. Talep yöntemleri, yeni bir cihaz oluştururken IMEI veya MEID, seri numarası, üretici adı ve modeli ile ChromeOS cihazlar için onaylanmış cihaz kimliği de dahil olmak üzere DeviceIdentifier
alanlarını validate.
Bir cihaz için nasıl hak talebinde bulunacağınız aşağıdaki snippet'te gösterilmektedir:
Java
// Identify the device to claim. DeviceIdentifier identifier = new DeviceIdentifier(); // The manufacturer value is optional but recommended for cellular devices identifier.setManufacturer("Google"); identifier.setImei("098765432109875"); // Create the body to connect the customer with the device. ClaimDeviceRequest body = new ClaimDeviceRequest(); body.setDeviceIdentifier(identifier); body.setCustomerId(customerId); body.setSectionType("SECTION_TYPE_ZERO_TOUCH"); // Claim the device. ClaimDeviceResponse response = service.partners().devices().claim(PARTNER_ID, body).execute();
.NET
// Identify the device to claim. var deviceIdentifier = new DeviceIdentifier { // The manufacturer value is optional but recommended for cellular devices Manufacturer = "Google", Imei = "098765432109875" }; // Create the body to connect the customer with the device. ClaimDeviceRequest body = new ClaimDeviceRequest { DeviceIdentifier = deviceIdentifier, CustomerId = CustomerId, SectionType = "SECTION_TYPE_ZERO_TOUCH" }; // Claim the device. var response = service.Partners.Devices.Claim(body, PartnerId).Execute();
Python
# Identify the device to claim. # The manufacturer value is optional but recommended for cellular devices device_identifier = {'manufacturer':'Google', 'imei':'098765432109875'} # Create the body to connect the customer with the device. request_body = {'deviceIdentifier':device_identifier, \ 'customerId':customer_id, \ 'sectionType':'SECTION_TYPE_ZERO_TOUCH'} # Claim the device. response = service.partners().devices().claim(partnerId=PARTNER_ID, body=request_body).execute()
Cihazlarla ilgili hak talebi iptal ediliyor
Kuruluşunuz, müşteriden alınan cihaz talebini iptal edebilir. Bir cihazın hak talebi iptal edildiğinde
el değmeden kayıttan kaldırılır. Bir bayi başka bir hesaba taşınmasını, iade edilmesini istediği veya yanlışlıkla hak talebinde bulunulan bir cihazla ilgili hak talebini iptal edebilir.
Müşterinin cihaz talebini iptal etmek için partners.devices.unclaim
veya partners.devices.unclaimAsync
yöntemini çağırın.
Satıcılar
Bayi ağınızdaki iş ortaklarını, küresel bir bayi ağındaki yerel operatörleri veya sizin adınıza cihaz satan herhangi bir kuruluşu temsil etmek için tedarikçi firmalarla kullanabilirsiniz. Tedarikçiler kullanıcılarınızı, müşterilerinizi ve cihazlarınızı ayırmanıza yardımcı olur:
- Oluşturduğunuz tedarikçi firmalar, el değmeden kayıt hesabınızı veya birbirinizin hesaplarını göremez.
- Tedarikçilerinizin müşterilerini ve cihazlarını görüntüleyebilir, tedarikçilerin cihazlarının kaydını iptal edebilirsiniz. Ancak, tedarikçilerinizin müşterilerine cihaz atayamazsınız.
Portalı kullanarak kuruluşunuz için tedarikçiler oluşturun. API'yi kullanamazsınız. Yeni bir tedarikçi firma oluşturmak için hesap rolünüz Sahip olmalıdır. Kuruluşunuzda tedarikçiler varsa tedarikçilerinizi listelemek için partners.vendors.list
, tedarikçilerinizin müşterilerini edinmek için ise partners.vendors.customers.list
numaralı telefonu arayabilirsiniz. Aşağıdaki örnekte, tedarikçilerin müşterileri için Hizmet Şartları durumunu gösteren bir rapor yazdırmak amacıyla her iki yöntem de kullanılmaktadır:
Java
// First, get the organization's vendors. String parentResource = String.format("partners/%d", PARTNER_ID); ListVendorsResponse results = service.partners().vendors().list(parentResource).execute(); if (results.getVendors() == null) { return; } // For each vendor, report the company name and a maximum 5 customers. for (Company vendor: results.getVendors()) { System.out.format("\n%s customers\n", vendor.getCompanyName()); System.out.println("---"); // Use the vendor's API resource name as the parent resource. AndroidProvisioningPartner.Partners.Vendors.Customers.List customerRequest = service.partners().vendors().customers().list(vendor.getName()); customerRequest.setPageSize(5); ListVendorCustomersResponse customerResponse = customerRequest.execute(); List<Company> customers = customerResponse.getCustomers(); if (customers == null) { System.out.println("No customers"); break; } else { for (Company customer: customers) { System.out.format("%s: %s\n", customer.getCompanyName(), customer.getTermsStatus()); } } }
.NET
// First, get the organization's vendors. var parentResource = String.Format("partners/{0}", PartnerId); var results = service.Partners.Vendors.List(parentResource).Execute(); if (results.Vendors == null) { return; } // For each vendor, report the company name and a maximum 5 customers. foreach (Company vendor in results.Vendors) { Console.WriteLine("\n{0} customers", vendor); Console.WriteLine("---"); // Use the vendor's API resource name as the parent resource. PartnersResource.VendorsResource.CustomersResource.ListRequest customerRequest = service.Partners.Vendors.Customers.List(vendor.Name); customerRequest.PageSize = 5; var customerResponse = customerRequest.Execute(); IList<Company> customers = customerResponse.Customers; if (customers == null) { Console.WriteLine("No customers"); break; } else { foreach (Company customer in customers) { Console.WriteLine("{0}: {1}", customer.Name, customer.TermsStatus); } } }
Python
# First, get the organization's vendors. parent_resource = 'partners/{0}'.format(PARTNER_ID) vendor_response = service.partners().vendors().list( parent=parent_resource).execute() if 'vendors' not in vendor_response: return # For each vendor, report the company name and a maximum 5 customers. for vendor in vendor_response['vendors']: print '\n{0} customers'.format(vendor['companyName']) print '---' # Use the vendor's API resource name as the parent resource. customer_response = service.partners().vendors().customers().list( parent=vendor['name'], pageSize=5).execute() if 'customers' not in customer_response: print 'No customers' break for customer in customer_response['customers']: print ' {0}: {1}'.format(customer['name'], customer['termsStatus'])
Cihaz koleksiyonunuz varsa cihaz için hangi bayinin veya satıcının hak talebinde bulunduğunu bilmeniz gerekebilir. Sayısal bayi kimliğini almak için bir cihazın talep kaydındaki resellerId
alanının değerini inceleyin.
Kuruluşunuz, satıcı tarafından hak talebinde bulunulan cihaz talebini iptal edebilir. Cihazları değiştiren diğer API çağrıları için API yöntemini çağırmadan önce kuruluşunuzun cihaz üzerinde hak talebinde bulunup bulunmadığını kontrol etmeniz gerekir. Aşağıdaki örnekte bunu nasıl yapabileceğiniz gösterilmektedir:
Java
// Get the devices claimed for two customers: one of our organization's // customers and one of our vendor's customers. FindDevicesByOwnerRequest body = new FindDevicesByOwnerRequest(); body.setSectionType("SECTION_TYPE_ZERO_TOUCH"); body.setCustomerId(Arrays.asList(resellerCustomerId, vendorCustomerId)); body.setLimit(MAX_PAGE_SIZE); FindDevicesByOwnerResponse response = service.partners().devices().findByOwner(PARTNER_ID, body).execute(); if (response.getDevices() == null) { return; } for (Device device: response.getDevices()) { // Confirm the device was claimed by our reseller and not a vendor before // updating metadata in another method. for (DeviceClaim claim: device.getClaims()) { if (claim.getResellerId() == PARTNER_ID) { updateDeviceMetadata(device.getDeviceId()); break; } } }
.NET
// Get the devices claimed for two customers: one of our organization's // customers and one of our vendor's customers. FindDevicesByOwnerRequest body = new FindDevicesByOwnerRequest { Limit = MaxPageSize, SectionType = "SECTION_TYPE_ZERO_TOUCH", CustomerId = new List<long?> { resellerCustomerId, vendorCustomerId } }; var response = service.Partners.Devices.FindByOwner(body, PartnerId).Execute(); if (response.Devices == null) { return; } foreach (Device device in response.Devices) { // Confirm the device was claimed by our reseller and not a vendor before // updating metadata in another method. foreach (DeviceClaim claim in device.Claims) { if (claim.ResellerId == PartnerId) { UpdateDeviceMetadata(device.DeviceId); break; } } }
Python
# Get the devices claimed for two customers: one of our organization's # customers and one of our vendor's customers. request_body = {'limit':MAX_PAGE_SIZE, \ 'pageToken':None, \ 'customerId':[reseller_customer_id, vendor_customer_id], \ 'sectionType':'SECTION_TYPE_ZERO_TOUCH'} response = service.partners().devices().findByOwner(partnerId=PARTNER_ID, body=request_body).execute() for device in response['devices']: # Confirm the device was claimed by our reseller and not a vendor before # updating metadata in another method. for claim in device['claims']: if claim['resellerId'] == PARTNER_ID: update_device_metadata(device['deviceId']) break
Uzun süren toplu işlemler
API, cihaz yöntemlerinin eşzamansız sürümlerini içerir.
Bu yöntemler, birçok cihazın toplu olarak işlenmesine olanak tanırken eşzamanlı yöntemler ise her API isteği için bir cihaz işler. Eşzamansız yöntem adlarının bir Async son eki vardır (ör. claimAsync
).
Eşzamansız API yöntemleri, işleme tamamlanmadan önce bir sonuç döndürür. Eşzamansız yöntemler, uygulamanızın (veya aracınızın) uzun süreli bir işlemin tamamlanmasını bekleyen kullanıcılarınıza yanıt vermeye devam etmesine de yardımcı olur. Uygulamanız, işlemin durumunu düzenli olarak kontrol etmelidir.
İşlemler
Uzun süren bir toplu işlemi izlemek için Operation
kullanıyorsunuz. Eşzamansız bir yönteme yapılan başarılı bir çağrı, yanıttaki işleme bir referans döndürür. Aşağıdaki JSON snippet'inde updateMetadataAsync
çağrısından sonra verilen tipik bir yanıt gösterilmektedir:
{
"name": "operations/apibatchoperation/1234567890123476789"
}
Her işlem, bağımsız görevlerin bir listesini içerir. İşlemde yer alan görevlerin durumu ve sonuçları hakkında bilgi edinmek için operations.get
çağrısını yapın. Aşağıdaki snippet'te bunu nasıl
yapabileceğiniz gösterilmektedir. Kendi uygulamanızda hataları ele almanız gerekir.
Java
// Build out the request body to apply the same order number to a customer's // purchase of 2 devices. UpdateMetadataArguments firstUpdate = new UpdateMetadataArguments(); firstUpdate.setDeviceMetadata(metadata); firstUpdate.setDeviceId(firstTargetDeviceId); UpdateMetadataArguments secondUpdate = new UpdateMetadataArguments(); secondUpdate.setDeviceMetadata(metadata); secondUpdate.setDeviceId(firstTargetDeviceId); // Start the device metadata update. UpdateDeviceMetadataInBatchRequest body = new UpdateDeviceMetadataInBatchRequest(); body.setUpdates(Arrays.asList(firstUpdate, secondUpdate)); Operation response = service .partners() .devices() .updateMetadataAsync(PARTNER_ID, body) .execute(); // Assume the metadata update started, so get the Operation for the update. Operation operation = service.operations().get(response.getName()).execute();
.NET
// Build out the request body to apply the same order number to a customer's // purchase of 2 devices. var updates = new List<UpdateMetadataArguments> { new UpdateMetadataArguments { DeviceMetadata = metadata, DeviceId = firstTargetDeviceId }, new UpdateMetadataArguments { DeviceMetadata = metadata, DeviceId = secondTargetDeviceId } }; // Start the device metadata update. UpdateDeviceMetadataInBatchRequest body = new UpdateDeviceMetadataInBatchRequest { Updates = updates }; var response = service.Partners.Devices.UpdateMetadataAsync(body, PartnerId).Execute(); // Assume the metadata update started, so get the Operation for the update. Operation operation = service.Operations.Get(response.Name).Execute();
Python
# Build out the request body to apply the same order number to a customer's # purchase of 2 devices. updates = [{'deviceMetadata':metadata,'deviceId':first_target_device_id}, {'deviceMetadata':metadata,'deviceId':second_target_device_id}] # Start the device metadata update. response = service.partners().devices().updateMetadataAsync( partnerId=PARTNER_ID, body={'updates':updates}).execute() # Assume the metadata update started, so get the Operation for the update. operation = service.operations().get(name=response['name']).execute()
Bir işlemin bitip bitmediğini öğrenmek için true
değerine sahip bir done
alanı için işlemi kontrol edin. done
eksikse veya false
eksikse işlem hâlâ çalışıyordur.
Yanıtlar
Bir işlem tamamlandıktan sonra API, bağımsız görevlerin tümü başarılı olsa veya hiçbiri başarılı olmasa bile işlemi sonuçla günceller. response
alanı, işlemdeki her cihazın işlenmesini ayrıntılı şekilde açıklayan bir DevicesLongRunningOperationResponse
nesnesidir.
Herhangi bir görevin başarısız olup olmadığını etkili bir şekilde tespit etmek ve büyük sonuç listelerinde yineleme yapmaktan kaçınmak için successCount
alanını inceleyin. DevicesLongRunningOperationResponse
öğesinin perDeviceStatus
alanı, işlemdeki her cihazla ilgili ayrıntıları veren OperationPerDevice
örneklerinin bir listesidir. Liste sırası, orijinal istekteki görevlerle eşleşiyor.
Her OperationPerDevice
görevi, bir result
alanı ve sunucu tarafından alınan isteğin hatırlatıcı özetini içerir. result
alanını kullanarak görevin başarılı veya başarısız olduğunu kontrol edebilirsiniz.
Aşağıdaki JSON snippet'i, updateMetadataAsync
işlevine yapılan bir çağrıdan sonra verilen tipik yanıtın bir kısmını göstermektedir:
"response": {
"perDeviceStatus": [
{
"result": {
"deviceId": "12345678901234567",
"status": "SINGLE_DEVICE_STATUS_SUCCESS"
},
"updateMetadata": {
"deviceId": "12345678901234567",
"deviceMetadata": {
"entries": {
"phonenumber": "+1 (800) 555-0100"
}
}
}
}
],
"successCount": 1
}
İlerleme durumunu izle
Uygulamanızın ilerleme durumunu izlemesi gerekiyorsa işlemi düzenli olarak yeniden getirmeniz gerekir. metadata
alanı, uygulamanızın çalışan bir işlemin en son ilerlemesini kontrol etmesine yardımcı olacak bir DevicesLongRunningOperationMetadata
örneği içerir. İşlemin ilerlemesini takip etmek için aşağıdaki tabloda listelenen DevicesLongRunningOperationMetadata
alanlarını kullanın:
Alan | Tipik kullanım |
---|---|
processingStatus
|
İşlem ilerledikçe BATCH_PROCESS_PENDING
BATCH_PROCESS_IN_PROGRESS ve ardından
BATCH_PROCESS_PROCESSED olarak değiştirilir. |
progress
|
İşlenen güncellemelerin yüzdesi. Uygulamanız, bitiş süresini tahmin etmek için
bunu kullanabilir. İşlem tamamlanırken progress değeri 100 olabileceğinden bir işlemin tamamlanıp sonuçlanmadığını öğrenmek için done alanını kontrol edin. |
devicesCount
|
İşlemdeki güncelleme sayısını gösterir. API bazı güncellemeleri ayrıştıramıyorsa bu sayı, isteğinizdeki güncelleme sayısından farklı olabilir. |
Aşağıdaki basitleştirilmiş örnekte, bir uygulamanın yoklama aralıklarını ayarlamak için ilerleme meta verilerini nasıl kullanabileceği gösterilmektedir. Uygulamanızda, anket için daha gelişmiş bir görev çalıştırıcıya ihtiyacınız olabilir. Ayrıca hata işlemeyi de eklemeniz gerekir.
Java
// Milliseconds between polling the API. private static long MIN_INTERVAL = 2000; private static long MAX_INTERVAL = 10000; // ... // Start the device metadata update. Operation response = service .partners() .devices() .updateMetadataAsync(PARTNER_ID, body) .execute(); String operationName = response.getName(); // Start polling for completion. long startTime = new Date().getTime(); while (true) { // Get the latest update on the operation's progress using the API. Operation operation = service.operations().get(operationName).execute(); if (operation.get("done") != null && operation.getDone()) { // The operation is finished. Print the status. System.out.format("Operation complete: %s of %s successful device updates\n", operation.getResponse().get("successCount"), operation.getMetadata().get("devicesCount")); break; } else { // Estimate how long the operation *should* take - within min and max value. BigDecimal opProgress = (BigDecimal) operation.getMetadata().get("progress"); double progress = opProgress.longValue(); long interval = MAX_INTERVAL; if (progress > 0) { interval = (long) ((new Date().getTime() - startTime) * ((100.0 - progress) / progress)); } interval = Math.max(MIN_INTERVAL, Math.min(interval, MAX_INTERVAL)); // Sleep until the operation should be complete. Thread.sleep(interval); } }
.NET
// Milliseconds between polling the API. private static double MinInterval = 2000; private static double MaxInterval = 10000; // ... // Start the device metadata update. var response = service.Partners.Devices.UpdateMetadataAsync(body, PartnerId).Execute(); var operationName = response.Name; // Start polling for completion. var startTime = DateTime.Now; while (true) { // Get the latest update on the operation's progress using the API. Operation operation = service.Operations.Get(operationName).Execute(); if (operation.Done == true) { // The operation is finished. Print the status. Console.WriteLine("Operation complete: {0} of {1} successful device updates", operation.Response["successCount"], operation.Metadata["devicesCount"]); break; } else { // Estimate how long the operation *should* take - within min and max value. double progress = (double)(long)operation.Metadata["progress"]; double interval = MaxInterval; if (progress > 0) { interval = DateTime.Now.Subtract(startTime).TotalMilliseconds * ((100.0 - progress) / progress); } interval = Math.Max(MinInterval, Math.Min(interval, MaxInterval)); // Sleep until the operation should be complete. System.Threading.Thread.Sleep((int)interval); } }
Python
# Seconds between polling the API. MIN_INTERVAL = 2; MAX_INTERVAL = 10; # ... # Start the device metadata update response = service.partners().devices().updateMetadataAsync( partnerId=PARTNER_ID, body={'updates':updates}).execute() op_name = response['name'] start_time = time.time() # Start polling for completion while True: # Get the latest update on the operation's progress using the API op = service.operations().get(name=op_name).execute() if 'done' in op and op['done']: # The operation is finished. Print the status. print('Operation complete: {0} of {1} successful device updates'.format( op['response']['successCount'], op['metadata']['devicesCount'] )) break else: # Estimate how long the operation *should* take - within min and max. progress = op['metadata']['progress'] interval = MIN_INTERVAL if progress > 0: interval = (time.time() - start_time) * ((100.0 - progress) / progress) interval = max(MIN_INTERVAL, min(interval, MAX_INTERVAL)) # Sleep until the operation should be complete. time.sleep(interval)
Uygulamanızın kullanıcıları açısından mantıklı bir anket yaklaşımı seçin. Bir işlemin tamamlanmasını bekleyen bazı uygulama kullanıcıları, düzenli ilerleme güncellemelerinden yararlanabilir.
Sayfalara ayrılmış sonuçlar
partners.devices.findByOwner
API yöntemi, çok büyük cihaz listeleri döndürebilir. Yanıt boyutunu azaltmak için bu ve diğer API yöntemleri (ör. partners.devices.findByIdentifier
) sayfalandırılmış sonuçları destekler. Sayfalı sonuçlar sayesinde uygulamanız, büyük listeleri her seferinde tek bir sayfa olacak şekilde tekrarlı bir şekilde isteyebilir ve işleyebilir.
API yöntemini çağırdıktan sonra, yanıtın nextPageToken
için bir değer içerip içermediğini kontrol edin. nextPageToken
, null
değilse uygulamanız yöntemi tekrar çağırarak başka bir cihaz sayfası getirmek için bunu kullanabilir. limit
parametresinde cihaz sayısı için bir üst sınır ayarlamanız gerekir. nextPageToken
değeri null
ise uygulamanız son sayfayı istemiştir.
Aşağıdaki örnek yöntemde, uygulamanızın cihaz listesini nasıl yazdırabileceği gösterilmektedir.
Java
private static long MAX_PAGE_SIZE = 10; // ... /** * Demonstrates how to loop through paginated lists of devices. * @param pageToken The token specifying which result page to return. * @throws IOException If the zero-touch API call fails. */ private void printDevices(String pageToken) throws IOException { // Create the request body to find the customer's devices. FindDevicesByOwnerRequest body = new FindDevicesByOwnerRequest(); body.setLimit(MAX_PAGE_SIZE); body.setSectionType("SECTION_TYPE_ZERO_TOUCH"); body.setCustomerId(Collections.singletonList(targetCustomerId)); // Call the API to get a page of Devices. Send a page token from the method // argument (might be None). If the page token is None, the API returns the first page. FindDevicesByOwnerResponse response = service.partners().devices().findByOwner(PARTNER_ID, body).execute(); if (response.getDevices() == null) { return; } // 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 and print the devices. if (response.getNextPageToken() != null) { this.printDevices(response.getNextPageToken()); } } // ... // Pass null to start printing the first page of devices. printDevices(null);
.NET
private static int MaxPageSize = 10; // ... /// <summary>Demonstrates how to loop through paginated lists of devices.</summary> /// <param name="pageToken">The token specifying which result page to return.</param> private void PrintDevices(string pageToken) { // Create the request body to find the customer's devices. FindDevicesByOwnerRequest body = new FindDevicesByOwnerRequest { PageToken = pageToken, Limit = MaxPageSize, SectionType = "SECTION_TYPE_ZERO_TOUCH", CustomerId = new List<long?> { targetCustomerId } }; // Call the API to get a page of Devices. Send a page token from the method // argument (might be None). If the page token is None, the API returns the first page. var response = service.Partners.Devices.FindByOwner(body, PartnerId).Execute(); if (response.Devices == null) { return; } // 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(response.NextPageToken); } } // ... // Pass null to start printing the first page of devices. PrintDevices(null);
Python
MAX_PAGE_SIZE = 10; # ... def print_devices(page_token): """Demonstrates how to loop through paginated lists of devices. Args: page_token: The token specifying which result page to return. """ # Create the body to find the customer's devices. request_body = {'limit':MAX_PAGE_SIZE, \ 'pageToken':page_token, \ 'customerId':[target_customer_id], \ 'sectionType':'SECTION_TYPE_ZERO_TOUCH'} # Call the API to get a page of Devices. Send a page token from the method # argument (might be None). If the page token is None, # the API returns the first page. response = service.partners().devices().findByOwner(partnerId=PARTNER_ID, body=request_body).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(response['nextPageToken']) # ... # Pass None to start printing the first page of devices. print_devices(None);
Sonraki adımlar
API'nin işleyiş şeklini öğrendiğinize göre Java, .NET veya Python için hızlı başlangıç kılavuzuyla verilen örnekleri deneyebilirsiniz.