כפי שמתואר במאמר סקירה כללית של Google Play Services, ערכות SDK שמבוססות על Google Play Services מגובות בשירותים שבמכשיר במכשירי Android שאושרו על ידי Google. כדי לחסוך בנפח האחסון ובזיכרון בכל המכשירים, חלק מהשירותים מותקנים לפי דרישה כשברור שמכשיר ספציפי דורש את הפונקציונליות הרלוונטית. לדוגמה, ערכת ML מספקת את האפשרות הזו כשמשתמשים במודלים ב-Google Play Services.
המקרה הנפוץ ביותר הוא הורדה והתקנה של שירות (או "מודול") במקביל לאפליקציה שנדרשת לה, על סמך התלות ב-AndroidManifest.xml
של ה-SDK. כדי להשיג שליטה רבה יותר, ממשקי ה-API להתקנת המודול מאפשרים לבדוק במפורש את הזמינות של המודול, לבקש את התקנת המודול, לעקוב אחר מצב הבקשות ולטפל בשגיאות.
כדי להבטיח את זמינות ה-API ב-ModuleInstallClient
, צריך לפעול לפי השלבים הבאים.
שימו לב שקטעי הקוד הבאים משתמשים ב-TensorFlow Lite SDK (play-services-tflite-java
) כספרייה לדוגמה, אבל השלבים האלה רלוונטיים לכל ספרייה המשולבת עם OptionalModuleApi
. נעדכן את המדריך הזה עם מידע נוסף כשנוסיף תמיכה בערכות SDK.
לפני שמתחילים
כדי להכין את האפליקציה שלך, בצע את השלבים המפורטים בקטעים הבאים.
דרישות מוקדמות לאפליקציה
יש לוודא שקובץ ה-build של האפליקציה משתמש בערכים הבאים:
minSdkVersion
של19
ומעלה
הגדרת האפליקציה
בקובץ
settings.gradle
ברמה העליונה, יש לכלול את מאגר Maven של Google ואת המאגר המרכזי של Maven בתוך הבלוקdependencyResolutionManagement
:dependencyResolutionManagement { repositories { google() mavenCentral() } }
בקובץ ה-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.3.0' implementation 'com.google.android.gms:play-services-tflite-java:16.2.0-beta02' }
בדיקת זמינות המודול
אחזור של מופע של
ModuleInstallClient
:Kotlin
val moduleInstallClient = ModuleInstall.getClient(context)
Java
ModuleInstallClient moduleInstallClient = ModuleInstall.getClient(context);
בודקים את הזמינות של מודול אופציונלי באמצעות
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… });
שליחה של בקשה להתקנה שנדחתה
אחזור של מופע של
ModuleInstallClient
:Kotlin
val moduleInstallClient = ModuleInstall.getClient(context)
Java
ModuleInstallClient moduleInstallClient = ModuleInstall.getClient(context);
שולחים את הבקשה שנדחתה:
Kotlin
val optionalModuleApi = TfLite.getClient(context) moduleInstallClient.deferredInstall(optionalModuleApi)
Java
OptionalModuleApi optionalModuleApi = TfLite.getClient(context); moduleInstallClient.deferredInstall(optionalModuleApi);
שליחת בקשה דחופה להתקנת מודול
אחזור של מופע של
ModuleInstallClient
:Kotlin
val moduleInstallClient = ModuleInstall.getClient(context)
Java
ModuleInstallClient moduleInstallClient = ModuleInstall.getClient(context);
(אופציונלי) יוצרים
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();
מגדירים את
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();
שולחים את בקשת ההתקנה:
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 תלות ב-framework של הזרקת תלות.
החלפת ModuleInstallClient
בטקסט FakeModuleInstallClient
בבדיקה
מוסיפים תלות:
בקובץ ה-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.0.0' }
יוצרים מודול 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); } }
מכניסים את
ModuleInstallClient
לפעילות:Kotlin
@AndroidEntryPoint class MyActivity: AppCompatActivity() { @Inject lateinit var moduleInstallClient: ModuleInstallClient ... }
Java
@AndroidEntryPoint public class MyActivity extends AppCompatActivity { @Inject ModuleInstallClient moduleInstallClient; ... }
החלפת הקישור בבדיקה:
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... }