הבטחת זמינות של ממשק API באמצעות ModuleInstallClient

כפי שמתואר במאמר סקירה כללית של Google Play Services, ערכות SDK שמופעלות על ידי Google Play Services מגובות על ידי שירותים ששמורים במכשיר במכשירי Android שאושרו על ידי Google. כדי לשמר נפח אחסון וזיכרון בכל המכשירים, חלק מהשירותים מותקנים על פי דרישה כשברור שמכשיר מסוים דורש את הפונקציונליות הרלוונטית. לדוגמה, ML Kit מאפשר לכם להשתמש במודלים ב-Google Play Services.

המצב הנפוץ ביותר הוא הורדה והתקנה של שירות (או 'מודול') במקביל לאפליקציה שדורשת אותו, על סמך התלות ב-AndroidManifest.xml של ה-SDK. כדי שתהיה לכם יותר שליטה, ממשקי ה-API להתקנת המודולים מאפשרים לבדוק באופן מפורש את זמינות המודול, לבקש את התקנת המודול, לעקוב אחרי מצב הבקשה ולטפל בשגיאות.

כדי לוודא שה-API זמין אצל ModuleInstallClient, צריך לפעול לפי השלבים הבאים. שימו לב שקטעי הקוד הבאים משתמשים ב-TensorFlow Lite SDK (play-services-tflite-java) כספרייה לדוגמה, אבל השלבים האלה רלוונטיים לכל ספרייה שמשולבת עם OptionalModuleApi. נוסיף עוד מידע במדריך הזה כשנוסיף עוד ערכות SDK.

לפני שמתחילים

כדי להכין את האפליקציה, צריך לבצע את השלבים בקטעים הבאים.

דרישות מוקדמות לאפליקציה

יש לוודא שקובץ ה-build של האפליקציה משתמש בערכים הבאים:

  • minSdkVersion של 19 ומעלה

הגדרת האפליקציה

  1. בקובץ settings.gradle ברמה העליונה, כוללים את מאגר Maven של Google ואת המאגר המרכזי של Maven בבלוק dependencyResolutionManagement:

    dependencyResolutionManagement {
        repositories {
            google()
            mavenCentral()
        }
    }
    
  2. מוסיפים את יחסי התלות של שירותי Google Play ל-play-services-base ול-play-services-tflite-java בקובץ ה-build של Gradle של המודול (בדרך כלל app/build.gradle):

    dependencies {
      implementation 'com.google.android.gms:play-services-base:18.5.0'
      implementation 'com.google.android.gms:play-services-tflite-java:16.2.0-beta02'
    }
    

בדיקת הזמינות של המודול

  1. מקבלים מופע של ModuleInstallClient:

    Kotlin

    val moduleInstallClient = ModuleInstall.getClient(context)
    

    Java

    ModuleInstallClient moduleInstallClient = ModuleInstall.getClient(context);
    
  2. בודקים את הזמינות של מודול אופציונלי באמצעות OptionalModuleApi שלו:

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

שליחה של בקשת התקנה שנדחתה

  1. מקבלים מופע של ModuleInstallClient:

    Kotlin

    val moduleInstallClient = ModuleInstall.getClient(context)
    

    Java

    ModuleInstallClient moduleInstallClient = ModuleInstall.getClient(context);
    
  2. שולחים את הבקשה בעיכוב:

    Kotlin

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

    Java

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

שליחת בקשה דחופה להתקנת מודול

  1. מקבלים מופע של ModuleInstallClient:

    Kotlin

    val moduleInstallClient = ModuleInstall.getClient(context)
    

    Java

    ModuleInstallClient moduleInstallClient = ModuleInstall.getClient(context);
    
  2. (אופציונלי) יוצרים InstallStatusListener כדי לטפל בעדכוני סטטוס ההתקנה.

    אם אתם רוצים לעקוב אחרי התקדמות ההורדה בממשק משתמש מותאם אישית (למשל, סרגל התקדמות), תוכלו ליצור InstallStatusListener כדי לקבל את העדכונים של סטטוס ההתקנה.

    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 ומוסיפים את OptionalModuleApi לבקשה:

    Kotlin

    val optionalModuleApi = TfLite.getClient(context)
    val moduleInstallRequest =
      ModuleInstallRequest.newBuilder()
        .addApi(optionalModuleApi)
        // Add more APIs if you would like to request multiple optional 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 optional modules
            //.addApi(...)
            // Set the listener if you need to monitor the download progress
            //.setListener(listener)
            .build();
    
  4. שולחים את בקשת ההתקנה:

    Kotlin

    moduleInstallClient
      .installModules(moduleInstallRequest)
      .addOnSuccessListener {
        if (it.areModulesAlreadyInstalled()) {
          // Modules are already installed when the request is sent.
        }
      }
      .addOnFailureListener {
        // Handle failure…
      }
    

    Java

    moduleInstallClient.installModules(moduleInstallRequest)
        .addOnSuccessListener(
            response -> {
              if (response.areModulesAlreadyInstalled()) {
                // Modules are already installed when the request is sent.
              }
            })
        .addOnFailureListener(
            e -> {
              // Handle failure...
            });
    

בדיקה מקומית באמצעות FakeModuleInstallClient

ערכות ה-SDK של Google Play Services מספקות את FakeModuleInstallClient כדי לאפשר לדמות את התוצאות של ממשקי ה-API להתקנת המודול בבדיקות באמצעות החדרת תלות.

דרישות מוקדמות לאפליקציה

מגדירים את האפליקציה לשימוש ב-Hilt תלות בהזרקה של מסגרת הזרקה של תלות.

מחליפים את ModuleInstallClient במחרוזת FakeModuleInstallClient בבדיקה

  1. הוספת תלות:

    בקובץ ה-build של Gradle של המודול (בדרך כלל app/build.gradle), מוסיפים לבדיקה את יחסי התלות של Google Play Services עבור play-services-base-testing.

      dependencies {
        // other dependencies...
    
        testImplementation 'com.google.android.gms:play-services-base-testing:16.1.0'
      }
    
  2. יוצרים מודול Hilt כדי לספק ModuleInstallClient:

    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 בפעילות:

    Kotlin

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

    Java

    @AndroidEntryPoint
    public class MyActivity extends AppCompatActivity {
      @Inject ModuleInstallClient moduleInstallClient;
    
      ...
    }
    
  4. החלפת הקישור בבדיקה:

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

הדמיה של זמינות המודול

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

סימולציה של התוצאה של בקשת התקנה שנדחתה

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

הדמיית התוצאה של בקשת התקנה דחופה

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