Verfügbarkeit von On-Demand-Modulen der Google Play-Dienste verwalten

Wie im Artikel Übersicht über Google Play-Dienste beschrieben, werden SDKs, die von Google Play-Diensten unterstützt werden, auf Google-zertifizierten Android-Geräten durch On-Device-Dienste unterstützt. Damit auf allen Geräten Speicherplatz und Arbeitsspeicher gespart werden, werden einige Dienste als Module bereitgestellt, die bei Bedarf installiert werden, wenn Ihre App die entsprechende Funktion benötigt. ML Kit bietet diese Option beispielsweise, wenn Modelle in Google Play-Diensten verwendet werden.

In den meisten Fällen werden die erforderlichen Module automatisch über das Google Play-Dienste SDK heruntergeladen und installiert, wenn Ihre App eine API verwendet, für die sie erforderlich sind. Möglicherweise möchten Sie jedoch mehr Kontrolle über den Prozess haben, z. B. wenn Sie die Nutzerfreundlichkeit verbessern möchten, indem Sie das Modul im Voraus installieren.

Die ModuleInstallClient API bietet folgende Möglichkeiten:

  • Prüfen Sie, ob die Module bereits auf dem Gerät installiert sind.
  • Fordern Sie die Installation der Module an.
  • Beobachten Sie den Installationsfortschritt.
  • Fehler während der Installation beheben

In diesem Leitfaden wird beschrieben, wie Sie mit ModuleInstallClient Module in Ihrer App verwalten. Die folgenden Code-Snippets verwenden das TensorFlow Lite SDK (play-services-tflite-java) als Beispiel. Diese Schritte gelten jedoch für jede Bibliothek, die in OptionalModuleApi integriert ist.

Hinweis

Führen Sie die Schritte in den folgenden Abschnitten aus, um Ihre App vorzubereiten.

Voraussetzungen für die App

Achten Sie darauf, dass in der Build-Datei Ihrer App die folgenden Werte verwendet werden:

  • minSdkVersion von mindestens 23

Eigene App konfigurieren

  1. Fügen Sie in der Datei settings.gradle auf oberster Ebene das Maven-Repository von Google und das Maven Central Repository im dependencyResolutionManagement-Block ein:

    dependencyResolutionManagement {
        repositories {
            google()
            mavenCentral()
        }
    }
    
  2. Fügen Sie in der Gradle-Build-Datei Ihres Moduls (in der Regel app/build.gradle) die Google Play-Dienste-Abhängigkeiten für play-services-base und play-services-tflite-java hinzu:

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

Prüfen, ob Module verfügbar sind

Bevor du versuchst, ein Modul zu installieren, kannst du prüfen, ob es bereits auf dem Gerät installiert ist. So können Sie unnötige Installationsanfragen vermeiden.

  1. Rufen Sie eine Instanz von ModuleInstallClient ab:

    Kotlin

    val moduleInstallClient = ModuleInstall.getClient(context)

    Java

    ModuleInstallClient moduleInstallClient = ModuleInstall.getClient(context);
  2. Prüfen Sie die Verfügbarkeit eines Moduls anhand seiner OptionalModuleApi. Diese API wird vom Google Play-Dienste SDK bereitgestellt, das Sie verwenden.

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

Verzögerte Installation anfordern

Wenn Sie das Modul nicht sofort benötigen, können Sie eine verzögerte Installation anfordern. So können die Google Play-Dienste das Modul im Hintergrund installieren, möglicherweise wenn das Gerät inaktiv und mit einem WLAN verbunden ist.

  1. Rufen Sie eine Instanz von ModuleInstallClient ab:

    Kotlin

    val moduleInstallClient = ModuleInstall.getClient(context)

    Java

    ModuleInstallClient moduleInstallClient = ModuleInstall.getClient(context);
  2. Senden Sie die zurückgestellte Anfrage:

    Kotlin

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

    Java

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

Dringende Modulinstallation anfordern

Wenn Ihre App das Modul sofort benötigt, können Sie eine dringende Installation anfordern. Das Modul wird dann so schnell wie möglich installiert, auch wenn dafür mobile Daten verwendet werden müssen.

  1. Rufen Sie eine Instanz von ModuleInstallClient ab:

    Kotlin

    val moduleInstallClient = ModuleInstall.getClient(context)

    Java

    ModuleInstallClient moduleInstallClient = ModuleInstall.getClient(context);
  2. Optional: Erstellen Sie ein InstallStatusListener, um den Installationsfortschritt zu überwachen.

    Wenn Sie den Downloadfortschritt in der Benutzeroberfläche Ihrer App anzeigen möchten (z. B. mit einer Fortschrittsanzeige), können Sie einen InstallStatusListener erstellen, um Updates zu erhalten.

    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. Konfigurieren Sie den ModuleInstallRequest und fügen Sie der Anfrage den OptionalModuleApi hinzu:

    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. Senden Sie die Installationsanfrage:

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

App mit FakeModuleInstallClient testen

Die SDKs für Google Play-Dienste enthalten die FakeModuleInstallClient, mit der Sie die Ergebnisse der APIs für die Modulinstallation in Tests mithilfe von Dependency Injection simulieren können. So können Sie das Verhalten Ihrer App in verschiedenen Szenarien testen, ohne sie auf einem echten Gerät bereitstellen zu müssen.

Voraussetzungen für die App

Konfigurieren Sie Ihre App für die Verwendung des Hilt-Frameworks für die Abhängigkeitsinjektion.

ModuleInstallClient im Test durch FakeModuleInstallClient ersetzen

Wenn Sie FakeModuleInstallClient in Ihren Tests verwenden möchten, müssen Sie die ModuleInstallClient-Bindung durch die Fake-Implementierung ersetzen.

  1. Abhängigkeit hinzufügen:

    Fügen Sie in der Gradle-Build-Datei Ihres Moduls (in der Regel app/build.gradle) die Google Play-Dienste-Abhängigkeiten für play-services-base-testing in Ihren Test ein.

      dependencies {
        // other dependencies...
    
        testImplementation 'com.google.android.gms:play-services-base-testing:16.2.0'
      }
    
  2. Erstellen Sie ein Hilt-Modul, um ModuleInstallClient bereitzustellen:

    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. Füge die ModuleInstallClient in die Aktivität ein:

    Kotlin

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

    Java

    @AndroidEntryPoint
    public class MyActivity extends AppCompatActivity {
      @Inject ModuleInstallClient moduleInstallClient;
    
      ...
    }
  4. Ersetzen Sie die Bindung im Test:

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

Verschiedene Szenarien simulieren

Mit FakeModuleInstallClient können Sie verschiedene Szenarien simulieren, z. B.:

  • Die Module sind bereits installiert.
  • Module sind auf dem Gerät nicht verfügbar.
  • Die Installation schlägt fehl.
  • Die Anfrage zur verzögerten Installation ist erfolgreich oder schlägt fehl.
  • Die dringende Installationsanfrage ist erfolgreich oder schlägt fehl.

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...
}

Ergebnis für eine Anfrage zur verzögerten Installation simulieren

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...
}

Ergebnis für eine dringende Installationsanfrage simulieren

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...
}