### Send Module Installation Request Source: https://developers.google.cn/android/guides/module-install-apis?hl=zh-cn Send the configured ModuleInstallRequest to initiate the module installation. Handle success by checking if modules were already installed and failure by implementing the onFailureListener. ```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... }); ``` -------------------------------- ### Monitor Module Installation Progress Source: https://developers.google.cn/android/guides/module-install-apis?hl=zh-cn Create an InstallStatusListener to receive updates on the module installation progress, such as download percentage. Unregister the listener when the installation reaches a terminal state (canceled, completed, or failed). ```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(); ``` -------------------------------- ### Get ModuleInstallClient Instance Source: https://developers.google.cn/android/guides/module-install-apis?hl=zh-cn Obtain an instance of ModuleInstallClient to interact with the module installation APIs. This is the first step in requesting module installation. ```kotlin val moduleInstallClient = ModuleInstall.getClient(context) ``` ```java ModuleInstallClient moduleInstallClient = ModuleInstall.getClient(context); ``` -------------------------------- ### Simulate Deferred Install Request Results (Kotlin) Source: https://developers.google.cn/android/guides/module-install-apis?hl=zh-cn Tests the outcomes of deferred installation requests, covering both successful and failed scenarios using FakeModuleInstallClient. ```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... } ``` -------------------------------- ### Simulate Deferred Install Request Results (Java) Source: https://developers.google.cn/android/guides/module-install-apis?hl=zh-cn Tests the outcomes of deferred installation requests, covering both successful and failed scenarios using FakeModuleInstallClient. ```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... } ``` -------------------------------- ### Example of Version Range Dependency Source: https://developers.google.cn/android/guides/releases?hl=pt-br Illustrates how a dependency on 'play-services-foo' within a version range in 'play-services-bar' necessitates future releases of 'play-services-foo' to start outside that range. ```text If `play-services-bar` has a dependency of `play-services-foo` with the range `[15.0.0, 16.0.0)`, a new release of `play-services-foo` will need to start with `16.0.0` to be outside of this range. ``` -------------------------------- ### Example of Version Range Dependency Source: https://developers.google.cn/android/guides/releases?hl=zh-cn Illustrates how version ranges in POM files affect dependency resolution and the requirement for future updates to start outside the defined range. ```text If `play-services-bar` depends on `play-services-foo` with a version range of `[15.0.0, 16.0.0)`, then a new version of `play-services-foo` must start with `16.0.0` to be outside this range. Any future version of `play-services-bar` will declare a "soft" requirement on a single version of `play-services-foo`. Any future version of `play-services-foo` will follow SemVer. ``` -------------------------------- ### Configure Module Install Request Source: https://developers.google.cn/android/guides/module-install-apis?hl=zh-cn Create a ModuleInstallRequest and add the desired OptionalModuleApi to it. You can add multiple APIs to request several modules at once. Optionally, set an InstallStatusListener to monitor download progress. ```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(); ``` -------------------------------- ### Play Services Cast Dependency Example Source: https://developers.google.cn/android/guides/releases?hl=zh-cn Example dependency for Play Services Cast. ```gradle com.google.android.gms:play-services-cast:16.0.0 ``` -------------------------------- ### Play Services Cast Framework Dependency Example Source: https://developers.google.cn/android/guides/releases?hl=zh-cn Example dependency for Play Services Cast Framework. ```gradle com.google.android.gms:play-services-cast-framework:16.0.0 ``` -------------------------------- ### PublisherAdView Video Controller Methods Source: https://developers.google.cn/android/guides/releases?hl=zh-tw The `PublisherAdView` class has been updated with methods to get and set video options. ```java Added `getVideoController()`, `setVideoOptions`, and `getVideoOptions()` methods to `PublisherAdView` class. ``` -------------------------------- ### NativeAdMapper AdChoices Content Methods Source: https://developers.google.cn/android/guides/releases?hl=zh-tw The `NativeAdMapper` class now includes methods to get and set AdChoices content. ```java Added `getAdChoicesContent()` and `setAdChoicesContent()` methods to `NativeAdMapper` class. ``` -------------------------------- ### Adding UnifiedNativeAd Class Source: https://developers.google.cn/android/guides/releases?hl=zh-cn Introduces the `UnifiedNativeAd` class for displaying app install or content ads and updates to the native advanced ad API to support it. ```java UnifiedNativeAd ``` -------------------------------- ### Request Server Auth Code for Backend Access Source: https://developers.google.cn/android/guides/releases?hl=zh-tw To get an access token for your backend, use the requestServerAuthCode and getServerAuthCode methods. The onUploadServerAuthCode callback and related functions have been removed. ```java GoogleSignInOptions signInOptions = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestServerAuthCode(SERVER_CLIENT_ID) .build(); ``` -------------------------------- ### Implementar InstallStatusListener para progreso de instalación (Java) Source: https://developers.google.cn/android/guides/module-install-apis?hl=es-419 Crea un oyente en Java para supervisar el progreso de la instalación del módulo. Útil para mostrar barras de progreso en la IU. El oyente se desregistra automáticamente cuando la instalación finaliza o falla. ```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(); ``` -------------------------------- ### Implementar InstallStatusListener para progreso de instalación (Kotlin) Source: https://developers.google.cn/android/guides/module-install-apis?hl=es-419 Crea un oyente para supervisar el progreso de la instalación del módulo. Útil para mostrar barras de progreso en la IU. El oyente se desregistra automáticamente cuando la instalación finaliza o falla. ```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() ``` -------------------------------- ### Get a Task Object Source: https://developers.google.cn/android/guides/tasks?hl=zh-cn Many APIs in Google Play services and Firebase return a Task object to represent an asynchronous operation. This example shows how to obtain a Task object for an anonymous sign-in operation. ```java Task task = FirebaseAuth.getInstance().signInAnonymously(); ``` -------------------------------- ### Request Deferred Module Installation Source: https://developers.google.cn/android/guides/module-install-apis?hl=pt-br Request a deferred installation for a module using its OptionalModuleApi. The Google Play Services will install the module in the background when the device is idle and connected to Wi-Fi. ```kotlin val optionalModuleApi = TfLite.getClient(context) moduleInstallClient.deferredInstall(optionalModuleApi) ``` -------------------------------- ### Generar informe de firma con Gradle Source: https://developers.google.cn/android/guides/client-auth?hl=es Ejecuta este comando de Gradle para obtener un informe completo de la información de firma de todas las variantes de tu aplicación, incluyendo los hashes MD5, SHA1 y SHA-256. ```bash ./gradlew signingReport ``` -------------------------------- ### Request Deferred Module Installation (Java) Source: https://developers.google.cn/android/guides/module-install-apis?hl=pt-br Request a deferred installation for a module using its OptionalModuleApi. The Google Play Services will install the module in the background when the device is idle and connected to Wi-Fi. ```java OptionalModuleApi optionalModuleApi = TfLite.getClient(context); moduleInstallClient.deferredInstall(optionalModuleApi); ``` -------------------------------- ### Obtener instancia de ModuleInstallClient (Java) Source: https://developers.google.cn/android/guides/module-install-apis?hl=es-419 Obtiene una instancia del cliente de instalación de módulos en Java. Este es el primer paso para solicitar la instalación de módulos. ```java ModuleInstallClient moduleInstallClient = ModuleInstall.getClient(context); ``` -------------------------------- ### Inyectar ModuleInstallClient en la actividad (Java) Source: https://developers.google.cn/android/guides/module-install-apis?hl=es Inyecta ModuleInstallClient en tu actividad usando Hilt para acceder a sus funcionalidades. ```java @AndroidEntryPoint public class MyActivity extends AppCompatActivity { @Inject ModuleInstallClient moduleInstallClient; ... } ``` -------------------------------- ### Simular módulos ya instalados (Kotlin) Source: https://developers.google.cn/android/guides/module-install-apis?hl=es Simula el escenario donde los módulos ya están instalados usando FakeModuleInstallClient. Asegúrate de resetear el cliente y establecer los módulos instalados. ```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... } ``` -------------------------------- ### Inyectar ModuleInstallClient en la actividad (Kotlin) Source: https://developers.google.cn/android/guides/module-install-apis?hl=es Inyecta ModuleInstallClient en tu actividad usando Hilt para acceder a sus funcionalidades. ```kotlin @AndroidEntryPoint class MyActivity: AppCompatActivity() { @Inject lateinit var moduleInstallClient: ModuleInstallClient ... } ``` -------------------------------- ### Imprimir huella digital del certificado desde un APK o AAB con Keytool Source: https://developers.google.cn/android/guides/client-auth?hl=es Utiliza `keytool` para imprimir la información del certificado directamente desde un archivo APK o AAB. Esto es útil si no tienes acceso al almacén de claves original. ```bash # APK file keytool -printcert -jarfile app.apk # AAB file keytool -printcert -jarfile app.aab ``` -------------------------------- ### Firebase Dependency Example Source: https://developers.google.cn/android/guides/releases?hl=es-419 Example illustrating how future versions of a library should declare a 'flexible' requirement on a single version of another library to avoid version range issues. ```gradle implementation 'com.google.firebase:firebase-core:+' ``` -------------------------------- ### Check API Availability and Get Last Location Source: https://developers.google.cn/android/guides/google-api-client?hl=zh-cn This snippet demonstrates how to check if the Fused Location Provider API is available on the device before attempting to get the last known location. ```APIDOC ## Check API Availability and Get Last Location ### Description This code snippet shows how to safely check if the Fused Location Provider API is available on the device using `GoogleApiAvailability.checkApiAvailability()` before proceeding to fetch the last known location. This prevents potential errors if the API is not supported or enabled. ### Method `GoogleApiAvailability.getInstance().checkApiAvailability(client).onSuccessTask { _ -> client.lastLocation }` (Kotlin) / `GoogleApiAvailability.getInstance().checkApiAvailability(client).onSuccessTask(unused -> client.getLastLocation())` (Java) ### Parameters - **context** (Context) - The context of the application or activity. ### Request Example ```kotlin fun getLastLocationIfApiAvailable(context: Context?): Task? { val client = getFusedLocationProviderClient(context) return GoogleApiAvailability.getInstance() .checkApiAvailability(client) .onSuccessTask { _ -> client.lastLocation } .addOnFailureListener { _ -> Log.d(TAG, "Location unavailable.")} } ``` ```java public Task getLastLocationIfApiAvailable(Context context) { FusedLocationProviderClient client = getFusedLocationProviderClient(context); return GoogleApiAvailability.getInstance() .checkApiAvailability(client) .onSuccessTask(unused -> client.getLastLocation()) .addOnFailureListener(e -> Log.d(TAG, "Location unavailable.")); } ``` ### Response #### Success Response - **Task** - A Task that, if successful, will contain the last known location. If the API is unavailable or an error occurs, the Task will be completed with an exception. #### Response Example (On success, the Task will resolve with a Location object. On failure, an exception will be thrown, and the `addOnFailureListener` will be invoked.) ```json { "status": "SUCCESS", "result": { "latitude": 37.7749, "longitude": -122.4194 } } ``` ``` -------------------------------- ### Get Last Known Location Source: https://developers.google.cn/android/guides/google-api-client?hl=zh-cn This snippet shows how to get the last known location using the Fused Location Provider client. It handles cases where the location might be null. ```APIDOC ## Get Last Known Location ### Description This code snippet demonstrates how to obtain the device's last known location using the `FusedLocationProviderClient` from Google Play Services. It includes handling for potential null values and assumes location permissions have been granted. ### Method `client.lastLocation` (Kotlin) / `client.getLastLocation()` (Java) ### Parameters None directly for the `lastLocation` call, but the `FusedLocationProviderClient` is initialized with a `Context` or `Activity`. ### Request Example ```kotlin // Code required for requesting location permissions omitted for brevity. val client = LocationServices.getFusedLocationProviderClient(this) // Get the last known location. In some rare situations, this can be null. client.lastLocation.addOnSuccessListener { location : Location? -> location?.let { // Logic to handle location object. } } ``` ```java // Code required for requesting location permissions omitted for brevity. FusedLocationProviderClient client = LocationServices.getFusedLocationProviderClient(this); // Get the last known location. In some rare situations, this can be null. client.getLastLocation() .addOnSuccessListener(this, location -> { if (location != null) { // Logic to handle location object. } }); ``` ### Response #### Success Response - **location** (Location?) - The last known location of the device, or null if unavailable. #### Response Example ```json { "latitude": 37.7749, "longitude": -122.4194, "accuracy": 10.0, "timestamp": 1678886400000 } ``` ``` -------------------------------- ### 媒體效果強化 Source: https://developers.google.cn/android/guides/setup?hl=zh-tw 用於媒體效果強化功能。 ```gradle com.google.android.gms:play-services-media-effect-enhancement:16.0.0-beta04 ``` -------------------------------- ### ML Kit 文件掃描器 Source: https://developers.google.cn/android/guides/setup?hl=zh-tw 用於 ML Kit 文件掃描器。 ```gradle com.google.android.gms:play-services-mlkit-document-scanner:16.0.0 ``` -------------------------------- ### Check API Availability and Get Last Location (Java) Source: https://developers.google.cn/android/guides/google-api-client?hl=zh-tw This Java snippet shows how to check if the location API is available before attempting to get the last known location. It uses `GoogleApiAvailability.checkApiAvailability` and `onSuccessTask`. ```APIDOC ## Check API Availability and Get Last Location (Java) ### Description This function checks if the necessary location services are available on the device before attempting to retrieve the last known location. It chains the availability check with the location retrieval task. ### Method `GoogleApiAvailability.getInstance().checkApiAvailability().onSuccessTask()` ### Endpoint N/A (SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```java public Task getLastLocationIfApiAvailable(Context context) { FusedLocationProviderClient client = getFusedLocationProviderClient(context); return GoogleApiAvailability.getInstance() .checkApiAvailability(client) .onSuccessTask(unused -> client.getLastLocation()) .addOnFailureListener(e -> Log.d(TAG, "Location unavailable.")); } ``` ### Response #### Success Response - **Task** - A Task that completes with the Location object if the API is available and the location is retrieved successfully. #### Response Example ```json { "example": "Task object representing the location retrieval" } ``` ```