إدارة مدى توفّر وحدات "خدمات Google Play" عند الطلب

كما هو موضّح في نظرة عامة على "خدمات Google Play" مقالة، تستند حِزم تطوير البرامج (SDK) التي توفّرها "خدمات Google Play" إلى خدمات على الجهاز فقط على أجهزة Android المعتمَدة من Google. للحفاظ على مساحة التخزين والذاكرة على جميع الأجهزة، يتم توفير بعض الخدمات كوحدات يتم تثبيتها عند الطلب عندما يحتاج تطبيقك إلى الوظائف ذات الصلة. على سبيل المثال، توفّر حزمة تعلّم الآلة هذا الخيار عند استخدام النماذج في "خدمات Google Play".

في معظم الحالات، تنزِّل حزمة تطوير البرامج (SDK) الخاصة بـ "خدمات Google Play" الوحدات الضرورية وتثبِّتها تلقائيًا عندما يستخدم تطبيقك واجهة برمجة تطبيقات تتطلّبها. ومع ذلك، قد تريد التحكّم بشكل أكبر في العملية، مثلاً عندما تريد تحسين تجربة المستخدم من خلال تثبيت الوحدة مسبقًا.

تمنحك واجهة برمجة التطبيقات ModuleInstallClient إمكانية تنفيذ ما يلي:

  • التحقّق ممّا إذا كانت الوحدات مثبَّتة على الجهاز
  • طلب تثبيت الوحدات
  • تتبُّع عملية التثبيت
  • معالجة الأخطاء أثناء عملية التثبيت

يوضّح لك هذا الدليل كيفية استخدام ModuleInstallClient لإدارة الوحدات في تطبيقك. يُرجى العِلم أنّ مقتطفات الرموز البرمجية التالية تستخدم حزمة TensorFlow Lite SDK (play-services-tflite-java) كمثال، ولكن تنطبق هذه الخطوات على أي مكتبة مدمَجة مع OptionalModuleApi.

قبل البدء

لإعداد تطبيقك، أكمل الخطوات الواردة في الأقسام التالية.

المتطلبات الأساسية للتطبيق

تأكَّد من أنّ ملف الإصدار في تطبيقك يستخدم القيم التالية:

  • minSdkVersion بقيمة 23 أو أعلى

إعداد تطبيقك

  1. في ملف settings.gradle ذي المستوى الأعلى، ضِّمن مستودع Maven من Google و مستودع Maven المركزي ضمن كتلة dependencyResolutionManagement:

    dependencyResolutionManagement {
        repositories {
            google()
            mavenCentral()
        }
    }
    
  2. في ملف Gradle الخاص بالإصدار (عادةً app/build.gradle)، أضِف تبعيات "خدمات Google Play" لـ play-services-base وplay-services-tflite-java:

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

التحقّق من توفّر الوحدات

قبل محاولة تثبيت وحدة، يمكنك التحقّق ممّا إذا كانت مثبَّتة على الجهاز. يساعدك ذلك في تجنُّب طلبات التثبيت غير الضرورية.

  1. احصل على مثيل من ModuleInstallClient:

    Kotlin

    val moduleInstallClient = ModuleInstall.getClient(context)

    جافا

    ModuleInstallClient moduleInstallClient = ModuleInstall.getClient(context);
  2. تحقَّق من توفّر وحدة باستخدام OptionalModuleApi الخاص بها. توفّر حزمة تطوير البرامج (SDK) الخاصة بـ "خدمات Google Play" التي تستخدمها واجهة برمجة التطبيقات هذه.

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

    جافا

    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" بتثبيت الوحدة في الخلفية، ربما عندما يكون الجهاز غير نشط ومتصلاً بشبكة Wi-Fi.

  1. احصل على مثيل من ModuleInstallClient:

    Kotlin

    val moduleInstallClient = ModuleInstall.getClient(context)

    جافا

    ModuleInstallClient moduleInstallClient = ModuleInstall.getClient(context);
  2. أرسِل الطلب المؤجَّل:

    Kotlin

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

    جافا

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

طلب تثبيت عاجل للوحدة

إذا كان تطبيقك بحاجة إلى الوحدة على الفور، يمكنك طلب تثبيت عاجل. سيحاول ذلك تثبيت الوحدة بأسرع ما يمكن، حتى إذا كان ذلك يعني استخدام بيانات الجوّال.

  1. احصل على مثيل من ModuleInstallClient:

    Kotlin

    val moduleInstallClient = ModuleInstall.getClient(context)

    جافا

    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()

    جافا

    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()

    جافا

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

    جافا

    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" السمة FakeModuleInstallClient للسماح لك بمحاكاة نتائج واجهات برمجة التطبيقات الخاصة بتثبيت الوحدات في الاختبارات باستخدام إدخال التبعية. يساعدك ذلك في اختبار سلوك تطبيقك في سيناريوهات مختلفة بدون الحاجة إلى نشره على جهاز حقيقي.

المتطلبات الأساسية للتطبيق

اضبط تطبيقك لاستخدام إطار عمل Hilt لإدخال التبعية.

استبدال ModuleInstallClient بـ FakeModuleInstallClient في الاختبار

لاستخدام FakeModuleInstallClient في اختباراتك، عليك استبدال ModuleInstallClient الربط بالتنفيذ الوهمي.

  1. أضِف التبعية:

    في ملف Gradle الخاص بالإصدار (عادةً app/build.gradle)، أضِف تبعيات "خدمات Google Play" لـ play-services-base-testing في اختبارك.

      dependencies {
        // other dependencies...
    
        testImplementation 'com.google.android.gms:play-services-base-testing:16.2.0'
      }
    
  2. أنشِئ وحدة Hilt لتوفير ModuleInstallClient:

    Kotlin

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

    جافا

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

    جافا

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

    جافا

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

جافا

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

جافا

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

جافا

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