İsteğe bağlı Google Play Hizmetleri modüllerinin kullanılabilirliğini yönetme

Google Play Hizmetleri'ne genel bakış makalesinde açıklandığı gibi, Google Play Hizmetleri tarafından desteklenen SDK'lar, Google sertifikalı Android cihazlardaki cihaz üzerinde hizmetler tarafından desteklenir. Tüm cihaz filosunda depolama alanından ve bellekten tasarruf etmek için bazı hizmetler, uygulamanız ilgili işlevi gerektirdiğinde isteğe bağlı olarak yüklenen modüller şeklinde sunulur. Örneğin, Google Play Hizmetleri'ndeki modelleri kullanırken ML Kiti bu seçeneği sunar.

Çoğu durumda, uygulamanız gerekli modülleri kullanan bir API kullandığında Google Play Hizmetleri SDK'sı gerekli modülleri otomatik olarak indirip yükler. Ancak modülü önceden yükleyerek kullanıcı deneyimini iyileştirmek istediğinizde olduğu gibi, süreç üzerinde daha fazla kontrol sahibi olmak isteyebilirsiniz.

ModuleInstallClient API'si ile şunları yapabilirsiniz:

  • Modüllerin cihazda yüklü olup olmadığını kontrol edin.
  • Modülleri yükleme isteğinde bulunma
  • Yükleme işleminin ilerleme durumunu izleyin.
  • Yükleme işlemi sırasında oluşan hataları işleme

Bu kılavuzda, uygulamanızdaki modülleri yönetmek için ModuleInstallClient aracını nasıl kullanacağınız gösterilmektedir. Aşağıdaki kod snippet'lerinde örnek olarak TensorFlow Lite SDK (play-services-tflite-java) kullanılmıştır ancak bu adımlar, OptionalModuleApi ile entegre edilmiş tüm kitaplıklar için geçerlidir.

Başlamadan önce

Uygulamanızı hazırlamak için aşağıdaki bölümlerde yer alan adımları tamamlayın.

Uygulama ön koşulları

Uygulamanızın derleme dosyasında aşağıdaki değerlerin kullanıldığından emin olun:

  • 23 veya daha yüksek bir minSdkVersion

Uygulamanızı yapılandırma

  1. Üst düzey settings.gradle dosyanızda, dependencyResolutionManagement bloğuna Google'ın Maven deposunu ve Maven merkezi deposunu ekleyin:

    dependencyResolutionManagement {
        repositories {
            google()
            mavenCentral()
        }
    }
    
  2. Modülünüzün Gradle derleme dosyasına (genellikle app/build.gradle) play-services-base ve play-services-tflite-java için Google Play Hizmetleri bağımlılıklarını ekleyin:

    dependencies {
      implementation 'com.google.android.gms:play-services-base:18.11.1'
      implementation 'com.google.android.gms:play-services-tflite-java:16.5.0'
    }
    

Modüllerin kullanılabilir olup olmadığını kontrol etme

Bir modülü yüklemeye çalışmadan önce cihazda zaten yüklü olup olmadığını kontrol edebilirsiniz. Bu sayede gereksiz yükleme isteklerini önleyebilirsiniz.

  1. ModuleInstallClient örneği alın:

    Kotlin

    val moduleInstallClient = ModuleInstall.getClient(context)

    Java

    ModuleInstallClient moduleInstallClient = ModuleInstall.getClient(context);
  2. OptionalModuleApi kullanarak bir modülün kullanılabilirliğini kontrol edin. Bu API, kullandığınız Google Play Hizmetleri SDK'sı tarafından sağlanır.

    Kotlin

    val optionalModuleApi = TfLite.getClient(context)
    moduleInstallClient
      .areModulesAvailable(optionalModuleApi)
      .addOnSuccessListener {
        if (it.areModulesAvailable()) {
          // Modules are present on the device...
        } else {
          // Modules are not present on the device...
        }
      }
      .addOnFailureListener {
        // Handle failure...
      }

    Java

    OptionalModuleApi optionalModuleApi = TfLite.getClient(context);
    moduleInstallClient
        .areModulesAvailable(optionalModuleApi)
        .addOnSuccessListener(
            response -> {
              if (response.areModulesAvailable()) {
                // Modules are present on the device...
              } else {
                // Modules are not present on the device...
              }
            })
        .addOnFailureListener(
            e -> {
              // Handle failure…
            });

Ertelenmiş yükleme isteğinde bulunma

Modüle hemen ihtiyacınız yoksa ertelenmiş yükleme isteğinde bulunabilirsiniz. Bu sayede Google Play Hizmetleri, modülü arka planda (cihaz boştayken ve kablosuz ağa bağlıyken) yükleyebilir.

  1. ModuleInstallClient örneği alın:

    Kotlin

    val moduleInstallClient = ModuleInstall.getClient(context)

    Java

    ModuleInstallClient moduleInstallClient = ModuleInstall.getClient(context);
  2. Ertelenen isteği gönderme:

    Kotlin

    val optionalModuleApi = TfLite.getClient(context)
    moduleInstallClient.deferredInstall(optionalModuleApi)

    Java

    OptionalModuleApi optionalModuleApi = TfLite.getClient(context);
    moduleInstallClient.deferredInstall(optionalModuleApi);

Acil modül kurulumu isteğinde bulunma

Uygulamanızın modüle hemen ihtiyacı varsa acil yükleme isteğinde bulunabilirsiniz. Bu işlem, mobil veri kullanmak anlamına gelse bile modülü mümkün olan en kısa sürede yüklemeye çalışır.

  1. ModuleInstallClient örneği alın:

    Kotlin

    val moduleInstallClient = ModuleInstall.getClient(context)

    Java

    ModuleInstallClient moduleInstallClient = ModuleInstall.getClient(context);
  2. (İsteğe bağlı) Yükleme ilerleme durumunu izlemek için bir InstallStatusListener oluşturun.

    İndirme işleminin ilerleme durumunu uygulamanızın kullanıcı arayüzünde göstermek istiyorsanız (ör. ilerleme çubuğuyla) güncellemeleri almak için bir InstallStatusListener oluşturabilirsiniz.

    Kotlin

    inner class ModuleInstallProgressListener : InstallStatusListener {
      override fun onInstallStatusUpdated(update: ModuleInstallStatusUpdate) {
        // Progress info is only set when modules are in the progress of downloading.
        update.progressInfo?.let {
          val progress = (it.bytesDownloaded * 100 / it.totalBytesToDownload).toInt()
          // Set the progress for the progress bar.
          progressBar.setProgress(progress)
        }
    
        if (isTerminateState(update.installState)) {
          moduleInstallClient.unregisterListener(this)
        }
      }
    
      fun isTerminateState(@InstallState state: Int): Boolean {
        return state == STATE_CANCELED || state == STATE_COMPLETED || state == STATE_FAILED
      }
    }
    
    val listener = ModuleInstallProgressListener()

    Java

    static final class ModuleInstallProgressListener implements InstallStatusListener {
        @Override
        public void onInstallStatusUpdated(ModuleInstallStatusUpdate update) {
          ProgressInfo progressInfo = update.getProgressInfo();
          // Progress info is only set when modules are in the progress of downloading.
          if (progressInfo != null) {
            int progress =
                (int)
                    (progressInfo.getBytesDownloaded() * 100 / progressInfo.getTotalBytesToDownload());
            // Set the progress for the progress bar.
            progressBar.setProgress(progress);
          }
          // Handle failure status maybe…
    
          // Unregister listener when there are no more install status updates.
          if (isTerminateState(update.getInstallState())) {
    
            moduleInstallClient.unregisterListener(this);
          }
        }
    
        public boolean isTerminateState(@InstallState int state) {
          return state == STATE_CANCELED || state == STATE_COMPLETED || state == STATE_FAILED;
        }
      }
    
    InstallStatusListener listener = new ModuleInstallProgressListener();
  3. ModuleInstallRequest öğesini yapılandırın ve OptionalModuleApi öğesini isteğe ekleyin:

    Kotlin

    val optionalModuleApi = TfLite.getClient(context)
    val moduleInstallRequest =
      ModuleInstallRequest.newBuilder()
        .addApi(optionalModuleApi)
        // Add more APIs if you would like to request multiple modules.
        // .addApi(...)
        // Set the listener if you need to monitor the download progress.
        // .setListener(listener)
        .build()

    Java

    OptionalModuleApi optionalModuleApi = TfLite.getClient(context);
    ModuleInstallRequest moduleInstallRequest =
        ModuleInstallRequest.newBuilder()
            .addApi(optionalModuleApi)
            // Add more API if you would like to request multiple modules
            //.addApi(...)
            // Set the listener if you need to monitor the download progress
            //.setListener(listener)
            .build();
  4. Yükleme isteğini gönderme:

    Kotlin

    moduleInstallClient
      .installModules(moduleInstallRequest)
      .addOnSuccessListener {
        if (it.areModulesAlreadyInstalled()) {
          // Modules are already installed when the request is sent.
        }
        // The install request has been sent successfully. This does not mean
        // the installation is completed. To monitor the install status, set an
        // InstallStatusListener to the ModuleInstallRequest.
      }
      .addOnFailureListener {
        // Handle failure…
      }

    Java

    moduleInstallClient.installModules(moduleInstallRequest)
        .addOnSuccessListener(
            response -> {
              if (response.areModulesAlreadyInstalled()) {
                // Modules are already installed when the request is sent.
              }
              // The install request has been sent successfully. This does not
              // mean the installation is completed. To monitor the install
              // status, set an InstallStatusListener to the
              // ModuleInstallRequest.
            })
        .addOnFailureListener(
            e -> {
              // Handle failure...
            });

Uygulamanızı FakeModuleInstallClient ile test etme

Google Play Hizmetleri SDK'ları, bağımlılık ekleme özelliğini kullanarak testlerde modül yükleme API'lerinin sonuçlarını simüle etmenize olanak tanıyan FakeModuleInstallClient sağlar. Bu sayede, uygulamanızı gerçek bir cihaza dağıtmanıza gerek kalmadan farklı senaryolardaki davranışını test edebilirsiniz.

Uygulama ön koşulları

Uygulamanızı Hilt bağımlılık ekleme çerçevesini kullanacak şekilde yapılandırın.

Testte ModuleInstallClient yerine FakeModuleInstallClient kullanın

Testlerinizde FakeModuleInstallClient kullanmak için ModuleInstallClient bağlamasını sahte uygulamayla değiştirmeniz gerekir.

  1. Bağımlılık ekleme:

    Modülünüzün Gradle derleme dosyasında (genellikle app/build.gradle), testinizde play-services-base-testing için Google Play Hizmetleri bağımlılıklarını ekleyin.

      dependencies {
        // other dependencies...
    
        testImplementation 'com.google.android.gms:play-services-base-testing:16.2.0'
      }
    
  2. ModuleInstallClient sağlamak için bir Hilt modülü oluşturun:

    Kotlin

    @Module
    @InstallIn(ActivityComponent::class)
    object ModuleInstallModule {
    
      @Provides
      fun provideModuleInstallClient(
        @ActivityContext context: Context
      ): ModuleInstallClient = ModuleInstall.getClient(context)
    }

    Java

    @Module
    @InstallIn(ActivityComponent.class)
    public class ModuleInstallModule {
      @Provides
      public static ModuleInstallClient provideModuleInstallClient(
        @ActivityContext Context context) {
        return ModuleInstall.getClient(context);
      }
    }
  3. ModuleInstallClient öğesini etkinliğe ekleyin:

    Kotlin

    @AndroidEntryPoint
    class MyActivity: AppCompatActivity() {
      @Inject lateinit var moduleInstallClient: ModuleInstallClient
    
      ...
    }

    Java

    @AndroidEntryPoint
    public class MyActivity extends AppCompatActivity {
      @Inject ModuleInstallClient moduleInstallClient;
    
      ...
    }
  4. Testte bağlamayı değiştirme:

    Kotlin

    @UninstallModules(ModuleInstallModule::class)
    @HiltAndroidTest
    class MyActivityTest {
      ...
      private val context:Context = ApplicationProvider.getApplicationContext()
      private val fakeModuleInstallClient = FakeModuleInstallClient(context)
      @BindValue @JvmField
      val moduleInstallClient: ModuleInstallClient = fakeModuleInstallClient
    
      ...
    }

    Java

    @UninstallModules(ModuleInstallModule.class)
    @HiltAndroidTest
    class MyActivityTest {
      ...
      private static final Context context = ApplicationProvider.getApplicationContext();
      private final FakeModuleInstallClient fakeModuleInstallClient = new FakeModuleInstallClient(context);
      @BindValue ModuleInstallClient moduleInstallClient = fakeModuleInstallClient;
    
      ...
    }

Farklı senaryoları simüle etme

FakeModuleInstallClient ile aşağıdaki gibi farklı senaryoları simüle edebilirsiniz:

  • Modüller zaten yüklü.
  • Modüller cihazda kullanılamıyor.
  • Yükleme işlemi başarısız olur.
  • Ertelenen yükleme isteği başarılı veya başarısız olur.
  • Acil yükleme isteği başarılı veya başarısız olur.

Kotlin

@Test
fun checkAvailability_available() {
  // Reset any previously installed modules.
  fakeModuleInstallClient.reset()

  val availableModule = TfLite.getClient(context)
  fakeModuleInstallClient.setInstalledModules(api)

  // Verify the case where modules are already available...
}

@Test
fun checkAvailability_unavailable() {
  // Reset any previously installed modules.
  fakeModuleInstallClient.reset()

  // Do not set any installed modules in the test.

  // Verify the case where modules unavailable on device...
}

@Test
fun checkAvailability_failed() {
  // Reset any previously installed modules.
  fakeModuleInstallClient.reset()

  fakeModuleInstallClient.setModulesAvailabilityTask(Tasks.forException(RuntimeException()))

  // Verify the case where an RuntimeException happened when trying to get module's availability...
}

Java

@Test
public void checkAvailability_available() {
  // Reset any previously installed modules.
  fakeModuleInstallClient.reset();

  OptionalModuleApi optionalModuleApi = TfLite.getClient(context);
  fakeModuleInstallClient.setInstalledModules(api);

  // Verify the case where modules are already available...
}

@Test
public void checkAvailability_unavailable() {
  // Reset any previously installed modules.
  fakeModuleInstallClient.reset();

  // Do not set any installed modules in the test.

  // Verify the case where modules unavailable on device...
}

@Test
public void checkAvailability_failed() {
  fakeModuleInstallClient.setModulesAvailabilityTask(Tasks.forException(new RuntimeException()));

  // Verify the case where an RuntimeException happened when trying to get module's availability...
}

Ertelenen yükleme isteği için sonucu simüle etme

Kotlin

@Test
fun deferredInstall_success() {
  fakeModuleInstallClient.setDeferredInstallTask(Tasks.forResult(null))

  // Verify the case where the deferred install request has been sent successfully...
}

@Test
fun deferredInstall_failed() {
  fakeModuleInstallClient.setDeferredInstallTask(Tasks.forException(RuntimeException()))

  // Verify the case where an RuntimeException happened when trying to send the deferred install request...
}

Java

@Test
public void deferredInstall_success() {
  fakeModuleInstallClient.setDeferredInstallTask(Tasks.forResult(null));

  // Verify the case where the deferred install request has been sent successfully...
}

@Test
public void deferredInstall_failed() {
  fakeModuleInstallClient.setDeferredInstallTask(Tasks.forException(new RuntimeException()));

  // Verify the case where an RuntimeException happened when trying to send the deferred install request...
}

Acil yükleme isteği için sonucu simüle etme

Kotlin

@Test
fun installModules_alreadyExist() {
  // Reset any previously installed modules.
  fakeModuleInstallClient.reset();

  OptionalModuleApi optionalModuleApi = TfLite.getClient(context);
  fakeModuleInstallClient.setInstalledModules(api);

  // Verify the case where the modules already exist when sending the install request...
}

@Test
fun installModules_withoutListener() {
  // Reset any previously installed modules.
  fakeModuleInstallClient.reset();

  // Verify the case where the urgent install request has been sent successfully...
}

@Test
fun installModules_withListener() {
  // Reset any previously installed modules.
  fakeModuleInstallClient.reset();

  // Generates a ModuleInstallResponse and set it as the result for installModules().
  val moduleInstallResponse = FakeModuleInstallUtil.generateModuleInstallResponse()
  fakeModuleInstallClient.setInstallModulesTask(Tasks.forResult(moduleInstallResponse))

  // Verify the case where the urgent install request has been sent successfully...

  // Generates some fake ModuleInstallStatusUpdate and send it to listener.
  val update = FakeModuleInstallUtil.createModuleInstallStatusUpdate(
    moduleInstallResponse.sessionId, STATE_COMPLETED)
  fakeModuleInstallClient.sendInstallUpdates(listOf(update))

  // Verify the corresponding updates are handled correctly...
}

@Test
fun installModules_failed() {
  fakeModuleInstallClient.setInstallModulesTask(Tasks.forException(RuntimeException()))

  // Verify the case where an RuntimeException happened when trying to send the urgent install request...
}

Java

@Test
public void installModules_alreadyExist() {
  // Reset any previously installed modules.
  fakeModuleInstallClient.reset();

  OptionalModuleApi optionalModuleApi = TfLite.getClient(context);
  fakeModuleInstallClient.setInstalledModules(api);

  // Verify the case where the modules already exist when sending the install request...
}

@Test
public void installModules_withoutListener() {
  // Reset any previously installed modules.
  fakeModuleInstallClient.reset();

  // Verify the case where the urgent install request has been sent successfully...
}

@Test
public void installModules_withListener() {
  // Reset any previously installed modules.
  fakeModuleInstallClient.reset();

  // Generates a ModuleInstallResponse and set it as the result for installModules().
  ModuleInstallResponse moduleInstallResponse =
      FakeModuleInstallUtil.generateModuleInstallResponse();
  fakeModuleInstallClient.setInstallModulesTask(Tasks.forResult(moduleInstallResponse));

  // Verify the case where the urgent install request has been sent successfully...

  // Generates some fake ModuleInstallStatusUpdate and send it to listener.
  ModuleInstallStatusUpdate update = FakeModuleInstallUtil.createModuleInstallStatusUpdate(
      moduleInstallResponse.getSessionId(), STATE_COMPLETED);
  fakeModuleInstallClient.sendInstallUpdates(ImmutableList.of(update));

  // Verify the corresponding updates are handled correctly...
}

@Test
public void installModules_failed() {
  fakeModuleInstallClient.setInstallModulesTask(Tasks.forException(new RuntimeException()));

  // Verify the case where an RuntimeException happened when trying to send the urgent install request...
}