Như mô tả trong bài viết Tổng quan về Dịch vụ Google Play, các SDK do Dịch vụ Google Play cung cấp được hỗ trợ bởi các dịch vụ trên thiết bị trên thiết bị Android được Google chứng nhận. Để tiết kiệm bộ nhớ và dung lượng lưu trữ trên toàn bộ thiết bị, một số dịch vụ được cung cấp dưới dạng mô-đun được cài đặt theo yêu cầu khi ứng dụng của bạn yêu cầu chức năng liên quan. Ví dụ: Bộ công cụ học máy cung cấp tuỳ chọn này khi sử dụng các mô hình trong Dịch vụ Google Play.
Trong hầu hết các trường hợp, SDK Dịch vụ Google Play sẽ tự động tải xuống và cài đặt các mô-đun cần thiết khi ứng dụng của bạn sử dụng một API yêu cầu các mô-đun đó. Tuy nhiên, bạn có thể muốn kiểm soát quy trình này chặt chẽ hơn, chẳng hạn như khi bạn muốn cải thiện trải nghiệm người dùng bằng cách cài đặt trước mô-đun.
API ModuleInstallClient
cho phép bạn:
- Kiểm tra xem các mô-đun đã được cài đặt trên thiết bị hay chưa.
- Yêu cầu cài đặt các mô-đun.
- Theo dõi tiến trình cài đặt.
- Xử lý lỗi trong quá trình cài đặt.
Hướng dẫn này cho bạn biết cách sử dụng ModuleInstallClient
để quản lý các mô-đun trong ứng dụng. Xin lưu ý rằng các đoạn mã sau đây sử dụng SDK TensorFlow Lite (play-services-tflite-java
) làm ví dụ, nhưng các bước này áp dụng cho mọi thư viện được tích hợp với OptionalModuleApi
.
Trước khi bắt đầu
Để chuẩn bị cho ứng dụng của bạn, hãy hoàn tất các bước trong những phần sau.
Điều kiện tiên quyết đối với ứng dụng
Đảm bảo rằng tệp bản dựng của ứng dụng sử dụng các giá trị sau:
- Một
minSdkVersion
từ23
trở lên
Định cấu hình ứng dụng
Trong tệp
settings.gradle
cấp cao nhất, hãy thêm kho lưu trữ Maven của Google và kho lưu trữ trung tâm Maven vào khốidependencyResolutionManagement
:dependencyResolutionManagement { repositories { google() mavenCentral() } }
Trong tệp bản dựng Gradle của mô-đun (thường là
app/build.gradle
), hãy thêm các phần phụ thuộc Dịch vụ Google Play choplay-services-base
và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' }
Kiểm tra xem có mô-đun hay không
Trước khi thử cài đặt một mô-đun, bạn có thể kiểm tra xem mô-đun đó đã được cài đặt trên thiết bị hay chưa. Điều này giúp bạn tránh được các yêu cầu cài đặt không cần thiết.
Tạo một thực thể của
ModuleInstallClient
:Kotlin
val moduleInstallClient = ModuleInstall.getClient(context)
Java
ModuleInstallClient moduleInstallClient = ModuleInstall.getClient(context);
Kiểm tra tình trạng sẵn có của một mô-đun bằng
OptionalModuleApi
của mô-đun đó. API này do SDK Dịch vụ Google Play mà bạn đang sử dụng cung cấp.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… });
Yêu cầu cài đặt bị trì hoãn
Nếu không cần mô-đun ngay lập tức, bạn có thể yêu cầu cài đặt trễ. Điều này cho phép Dịch vụ Google Play cài đặt mô-đun ở chế độ nền, có thể là khi thiết bị ở trạng thái rảnh và kết nối với Wi-Fi.
Tạo một thực thể của
ModuleInstallClient
:Kotlin
val moduleInstallClient = ModuleInstall.getClient(context)
Java
ModuleInstallClient moduleInstallClient = ModuleInstall.getClient(context);
Gửi yêu cầu bị trì hoãn:
Kotlin
val optionalModuleApi = TfLite.getClient(context) moduleInstallClient.deferredInstall(optionalModuleApi)
Java
OptionalModuleApi optionalModuleApi = TfLite.getClient(context); moduleInstallClient.deferredInstall(optionalModuleApi);
Yêu cầu cài đặt mô-đun khẩn cấp
Nếu ứng dụng của bạn cần mô-đun ngay lập tức, bạn có thể yêu cầu cài đặt khẩn cấp. Thao tác này sẽ cố gắng cài đặt mô-đun nhanh nhất có thể, ngay cả khi phải sử dụng dữ liệu di động.
Tạo một thực thể của
ModuleInstallClient
:Kotlin
val moduleInstallClient = ModuleInstall.getClient(context)
Java
ModuleInstallClient moduleInstallClient = ModuleInstall.getClient(context);
(Không bắt buộc) Tạo
InstallStatusListener
để theo dõi tiến trình cài đặt.Nếu muốn hiển thị tiến trình tải xuống trong giao diện người dùng của ứng dụng (ví dụ: bằng thanh tiến trình), bạn có thể tạo
InstallStatusListener
để nhận thông tin cập nhật.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();
Định cấu hình
ModuleInstallRequest
và thêmOptionalModuleApi
vào yêu cầu: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();
Gửi yêu cầu cài đặt:
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... });
Kiểm thử ứng dụng bằng FakeModuleInstallClient
SDK Dịch vụ Google Play cung cấp FakeModuleInstallClient
để cho phép bạn mô phỏng kết quả của các API cài đặt mô-đun trong kiểm thử bằng cách chèn phần phụ thuộc. Điều này giúp bạn kiểm thử hành vi của ứng dụng trong nhiều tình huống mà không cần triển khai ứng dụng đó trên thiết bị thực.
Điều kiện tiên quyết đối với ứng dụng
Định cấu hình ứng dụng để sử dụng khung chèn phần phụ thuộc Hilt.
Thay thế ModuleInstallClient
bằng FakeModuleInstallClient
trong kiểm thử
Để sử dụng FakeModuleInstallClient
trong các bài kiểm thử, bạn cần thay thế liên kết ModuleInstallClient
bằng cách triển khai giả mạo.
Thêm phần phụ thuộc:
Trong tệp bản dựng Gradle của mô-đun (thường là
app/build.gradle
), hãy thêm các phần phụ thuộc Dịch vụ Google Play choplay-services-base-testing
trong kiểm thử.dependencies { // other dependencies... testImplementation 'com.google.android.gms:play-services-base-testing:16.1.0' }
Tạo mô-đun Hilt để cung cấp
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); } }
Chèn
ModuleInstallClient
vào hoạt động:Kotlin
@AndroidEntryPoint class MyActivity: AppCompatActivity() { @Inject lateinit var moduleInstallClient: ModuleInstallClient ... }
Java
@AndroidEntryPoint public class MyActivity extends AppCompatActivity { @Inject ModuleInstallClient moduleInstallClient; ... }
Thay thế liên kết trong kiểm thử:
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; ... }
Mô phỏng nhiều tình huống
Với FakeModuleInstallClient
, bạn có thể mô phỏng nhiều tình huống, chẳng hạn như:
- Các mô-đun đã được cài đặt.
- Không có mô-đun trên thiết bị.
- Quá trình cài đặt không thành công.
- Yêu cầu cài đặt bị trì hoãn thành công hoặc không thành công.
- Yêu cầu cài đặt khẩn cấp thành công hoặc không thành công.
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... }
Mô phỏng kết quả cho yêu cầu cài đặt bị trì hoãn
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... }
Mô phỏng kết quả cho yêu cầu cài đặt khẩn cấp
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... }