Compartir a través de


Habilitación de notificaciones push en Android

Las notificaciones push permiten a los clientes recibir notificaciones de mensajes entrantes y otras operaciones que se producen en un subproceso de chat cuando la aplicación móvil no se ejecuta en primer plano. Azure Communication Services admite una lista de eventos a los que se puede suscribir.

Nota:

Las notificaciones push de chat son compatibles con Android SDK en versiones a partir de 1.1.0-beta.4 y 1.1.0. Se recomienda usar la versión 2.0.0 o posterior, ya que las versiones anteriores tienen un problema conocido con la renovación del registro. Los pasos de 8 a 12 solo son necesarios para las versiones iguales o superiores a 2.0.0.

  1. Configure Firebase Cloud Messaging para el proyecto ChatQuickstart. Complete los pasos Create a Firebase project, Register your app with Firebase, Add a Firebase configuration file, Add Firebase SDKs to your appy Edit your app manifest en la documentación de Firebase.

  2. Cree un centro de notificaciones dentro de la misma suscripción que el recurso de Communication Services, configure la configuración de Firebase Cloud Messaging para el centro de notificaciones y vincule el centro de notificaciones al recurso de Communication Services. Consulte Aprovisionamiento del Centro de notificaciones.

  3. Cree un nuevo archivo llamado MyFirebaseMessagingService.java en el mismo directorio donde MainActivity.java reside. Copie el código siguiente en MyFirebaseMessagingService.java. Debe reemplazar <your_package_name> con el nombre del paquete usado en MainActivity.java. Puede usar su propio valor para <your_intent_name>. Use este valor en el paso 6.

       package <your_package_name>;
    
       import android.content.Intent;
       import android.util.Log;
    
       import androidx.localbroadcastmanager.content.LocalBroadcastManager;
    
       import com.azure.android.communication.chat.models.ChatPushNotification;
       import com.google.firebase.messaging.FirebaseMessagingService;
       import com.google.firebase.messaging.RemoteMessage;
    
       import java.util.concurrent.Semaphore;
    
       public class MyFirebaseMessagingService extends FirebaseMessagingService {
           private static final String TAG = "MyFirebaseMsgService";
           public static Semaphore initCompleted = new Semaphore(1);
    
           @Override
           public void onMessageReceived(RemoteMessage remoteMessage) {
               try {
                   Log.d(TAG, "Incoming push notification.");
    
                   initCompleted.acquire();
    
                   if (remoteMessage.getData().size() > 0) {
                       ChatPushNotification chatPushNotification =
                           new ChatPushNotification().setPayload(remoteMessage.getData());
                       sendPushNotificationToActivity(chatPushNotification);
                   }
    
                   initCompleted.release();
               } catch (InterruptedException e) {
                   Log.e(TAG, "Error receiving push notification.");
               }
           }
    
           private void sendPushNotificationToActivity(ChatPushNotification chatPushNotification) {
               Log.d(TAG, "Passing push notification to Activity: " + chatPushNotification.getPayload());
               Intent intent = new Intent("<your_intent_name>");
               intent.putExtra("PushNotificationPayload", chatPushNotification);
               LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
           }
       }
    
    
  4. En la parte superior del archivo MainActivity.java, agregue las siguientes instrucciones de importación:

       import android.content.BroadcastReceiver;
       import android.content.Context;
       import android.content.Intent;
       import android.content.IntentFilter;
    
       import androidx.localbroadcastmanager.content.LocalBroadcastManager;
       import com.azure.android.communication.chat.models.ChatPushNotification;
       import com.google.android.gms.tasks.OnCompleteListener;
       import com.google.android.gms.tasks.Task;
       import com.google.firebase.messaging.FirebaseMessaging;
    
  5. Agregue el siguiente código a la clase MainActivity:

       private BroadcastReceiver firebaseMessagingReceiver = new BroadcastReceiver() {
           @Override
           public void onReceive(Context context, Intent intent) {
               ChatPushNotification pushNotification =
                   (ChatPushNotification) intent.getParcelableExtra("PushNotificationPayload");
    
               Log.d(TAG, "Push Notification received in MainActivity: " + pushNotification.getPayload());
    
               boolean isHandled = chatAsyncClient.handlePushNotification(pushNotification);
               if (!isHandled) {
                   Log.d(TAG, "No listener registered for incoming push notification!");
               }
           }
       };
    
    
       private void startFcmPushNotification() {
           FirebaseMessaging.getInstance().getToken()
               .addOnCompleteListener(new OnCompleteListener<String>() {
                   @Override
                   public void onComplete(@NonNull Task<String> task) {
                       if (!task.isSuccessful()) {
                           Log.w(TAG, "Fetching FCM registration token failed", task.getException());
                           return;
                       }
    
                       // Get new FCM registration token
                       String token = task.getResult();
    
                       // Log and toast
                       Log.d(TAG, "Fcm push token generated:" + token);
                       Toast.makeText(MainActivity.this, token, Toast.LENGTH_SHORT).show();
    
                       chatAsyncClient.startPushNotifications(token, new Consumer<Throwable>() {
                           @Override
                           public void accept(Throwable throwable) {
                               Log.w(TAG, "Registration failed for push notifications!", throwable);
                           }
                       });
                   }
               });
       }
    
    
  6. Actualice la función onCreate en MainActivity.

       @Override
       protected void onCreate(Bundle savedInstanceState) {
           super.onCreate(savedInstanceState);
           setContentView(R.layout.activity_main);
    
           LocalBroadcastManager
               .getInstance(this)
               .registerReceiver(
                   firebaseMessagingReceiver,
                   new IntentFilter("<your_intent_name>"));
       }
    
  7. Coloque el código siguiente después del comentario <RECEIVE CHAT MESSAGES> en MainActivity:

   startFcmPushNotification();

   chatAsyncClient.addPushNotificationHandler(CHAT_MESSAGE_RECEIVED, (ChatEvent payload) -> {
       Log.i(TAG, "Push Notification CHAT_MESSAGE_RECEIVED.");
       ChatMessageReceivedEvent event = (ChatMessageReceivedEvent) payload;
       // You code to handle ChatMessageReceived event
   });
  1. Agregue el xmlns:tools campo al AndroidManifest.xml archivo:
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.azure.android.communication.chat.sampleapp">
  1. Deshabilite el inicializador predeterminado para WorkManager en AndroidManifest.xml:
    <!-- Disable the default initializer of WorkManager so that we could override it in MyAppConfiguration  -->
    <provider
        android:name="androidx.startup.InitializationProvider"
        android:authorities="${applicationId}.androidx-startup"
        android:exported="false"
        tools:node="merge">
      <!-- If you are using androidx.startup to initialize other components -->
      <meta-data
          android:name="androidx.work.WorkManagerInitializer"
          android:value="androidx.startup"
          tools:node="remove" />
    </provider>
    <!-- End of Disabling default initializer of WorkManager -->
  1. Agregue la WorkManager dependencia al build.gradle archivo:
    def work_version = "2.7.1"
    implementation "androidx.work:work-runtime:$work_version"
  1. Agregue un inicializador personalizado WorkManager mediante la creación de una clase que implemente Configuration.Provider:
    public class MyAppConfiguration extends Application implements Configuration.Provider {
        Consumer<Throwable> exceptionHandler = new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) {
                Log.i("YOUR_TAG", "Registration failed for push notifications!" + throwable.getMessage());
            }
        };
    
        @Override
        public void onCreate() {
            super.onCreate();
            // Initialize application parameters here
            WorkManager.initialize(getApplicationContext(), getWorkManagerConfiguration());
        }
    
        @NonNull
        @Override
        public Configuration getWorkManagerConfiguration() {
            return new Configuration.Builder().
                setWorkerFactory(new RegistrationRenewalWorkerFactory(COMMUNICATION_TOKEN_CREDENTIAL, exceptionHandler)).build();
        }
    }

Explicación del código anterior: El inicializador predeterminado de WorkManager está deshabilitado en el paso 9. Este paso implementa Configuration.Provider para proporcionar un personalizado WorkFactory, que es responsable de crear WorkerManager durante el tiempo de ejecución.

Si la aplicación se integra con Azure Functions, inicialice los parámetros de la aplicación en el método onCreate(). Se llama al método getWorkManagerConfiguration() cuando se inicia la aplicación, antes de que se creen objetos de actividad, servicio o receptor (excepto proveedores de contenido), por lo que los parámetros de la aplicación se pueden inicializar antes de su uso. Para obtener más información, consulte la aplicación de chat de ejemplo.

  1. Agregue el android:name=.MyAppConfiguration campo , que usa el nombre de clase del paso 11, en AndroidManifest.xml:
<application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:theme="@style/Theme.AppCompat"
      android:supportsRtl="true"
      android:name=".MyAppConfiguration"
>