ניהול הזמינות של מודולים של Google Play Services על פי דרישה

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

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

ממשק ה-API של ModuleInstallClient מאפשר לכם:

  • בודקים אם המודולים כבר מותקנים במכשיר.
  • מבקשים להתקין את המודולים.
  • עוקבים אחרי התקדמות ההתקנה.
  • טיפול בשגיאות במהלך תהליך ההתקנה.

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

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

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

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

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

  • minSdkVersion של 23 או יותר

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

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

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

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

איך בודקים אם המודולים זמינים

לפני שמנסים להתקין מודול, אפשר לבדוק אם הוא כבר מותקן במכשיר. כך תוכלו להימנע מבקשות התקנה מיותרות.

  1. אחזור של מופע של ModuleInstallClient:

    Kotlin

    val moduleInstallClient = ModuleInstall.getClient(context)

    Java

    ModuleInstallClient moduleInstallClient = ModuleInstall.getClient(context);
  2. בודקים את הזמינות של מודול באמצעות OptionalModuleApi שלו. ממשק ה-API הזה מסופק על ידי ערכת ה-SDK של Google Play Services שבה אתם משתמשים.

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

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

אם אתם לא צריכים את המודול באופן מיידי, אתם יכולים לבקש התקנה מושהית. כך מערכת Google Play Services יכולה להתקין את המודול ברקע, אולי כשהמכשיר לא פעיל ומחובר ל-Wi-Fi.

  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 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. שולחים את בקשת ההתקנה:

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

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

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

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

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

מחליפים את ModuleInstallClient ב-FakeModuleInstallClient בבדיקה

כדי להשתמש ב-FakeModuleInstallClient בבדיקות, צריך להחליף את קישור ה-ModuleInstallClient בהטמעה המזויפת.

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

סימולציה של תרחישים שונים

בעזרת 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...
}