Compartir a través de


Incorporación de notificaciones push a la aplicación de Xamarin.Android

Información general

En este tutorial, agregará notificaciones push al proyecto de inicio rápido de Xamarin.Android para que se envíe una notificación push al dispositivo cada vez que se inserte un registro.

Si no usa el proyecto de servidor de inicio rápido descargado, necesitará el paquete de extensión de notificación push. Para más información, consulte la guía Trabajar con el SDK del servidor back-end de .NET para Azure Mobile Apps .

Prerrequisitos

Este tutorial requiere la configuración:

Configuración de un centro de notificaciones

La característica Mobile Apps de Azure App Service usa Azure Notification Hubs para enviar notificaciones push, por lo tanto, configurará un centro de notificaciones para tu aplicación móvil.

  1. En Azure Portal, vaya a App Services y seleccione el back-end de la aplicación. En Configuración, seleccione Enviar.

  2. Para agregar un recurso del centro de notificaciones a la aplicación, seleccione Conectar. Puede crear un centro o conectarse a uno existente.

    Configura un centro

Ahora ha conectado un centro de notificaciones al proyecto de back-end de Mobile Apps. Más adelante, configure este centro de notificaciones para conectarse a un sistema de notificaciones de plataforma (PNS) para insertar en los dispositivos.

Habilitación de Firebase Cloud Messaging

  1. Inicie sesión en la consola de Firebase. Si aún no tiene uno, cree un nuevo proyecto de Firebase.

  2. Después de crear el proyecto, seleccione Agregar Firebase a la aplicación Android.

    Incorporación de Firebase a la aplicación Android

  3. En la página Agregar Firebase a la aplicación android , siga estos pasos:

    1. Para el nombre del paquete de Android, copie el valor de applicationId en el archivo build.gradle de la aplicación. En este ejemplo, es com.fabrikam.fcmtutorial1app.

      Especificar el nombre del paquete

    2. Seleccione Registrar aplicación.

  4. Seleccione Descargar google-services.json, guarde el archivo en la carpeta de la aplicación del proyecto y, a continuación, seleccione Siguiente.

    Descargar google-services.json

  5. Realice los siguientes cambios de configuración en el proyecto en Android Studio.

    1. En el archivo build.gradle de nivel de proyecto (<project>/build.gradle), agregue la siguiente instrucción a la sección dependencias .

      classpath 'com.google.gms:google-services:4.0.1'
      
    2. En el archivo build.gradle de nivel de aplicación (<project>/<app-module>/build.gradle), agregue las siguientes instrucciones a la sección de dependencias .

      implementation 'com.google.firebase:firebase-core:16.0.8'
      implementation 'com.google.firebase:firebase-messaging:17.3.4'
      
    3. Agregue la siguiente línea al final del archivo app-level build.gradle después de la sección de dependencias.

      apply plugin: 'com.google.gms.google-services'
      
    4. Seleccione Sincronizar ahora en la barra de herramientas.

      cambios de configuración de build.gradle

  6. Seleccione Siguiente.

  7. Seleccione Omitir este paso.

    Omitir el último paso

  8. En la consola Firebase, seleccione el icono de la rueda dentada del proyecto. A continuación, seleccione Configuración del proyecto.

    Seleccione Configuración del proyecto.

  9. Si no ha descargado el archivo google-services.json en la carpeta de la aplicación del proyecto de Android Studio, puede hacerlo en esta página.

  10. Cambie a la pestaña Mensajería en la nube en la parte superior.

  11. Copie y guarde la clave del servidor para su uso posterior. Usas este valor para configurar el concentrador.

Configurar Azure para enviar solicitudes de inserción

  1. En Azure Portal, haga clic en Examinar todos los>servicios de aplicaciones y, a continuación, haga clic en el back-end de Mobile Apps. En Configuración, haga clic en Notificación de App Service y, a continuación, haga clic en el nombre del centro de notificaciones.

  2. Vaya a Google (GCM), escriba el valor de Clave del servidor que obtuvo de Firebase en el procedimiento anterior y, a continuación, haga clic en Guardar.

    Establecimiento de la clave de API en el portal

El back-end de Mobile Apps ahora está configurado para usar Firebase Cloud Messaging. Esto le permite enviar notificaciones push a la aplicación que se ejecuta en un dispositivo Android mediante el centro de notificaciones.

Actualización del proyecto de servidor para enviar notificaciones push

En esta sección, actualizará el código del proyecto de back-end de Mobile Apps existente para enviar una notificación push cada vez que se agregue un nuevo elemento. Este proceso se basa en la característica de plantilla de Azure Notification Hubs, que permite notificaciones multiplataforma. Los distintos clientes se registran para las notificaciones push mediante plantillas, y una única notificación universal puede alcanzar a todas las plataformas cliente.

Elija uno de los procedimientos siguientes que coincida con el tipo de proyecto back-end, ya sea back-end de .NET o Node.js back-end.

Proyecto back-end de .NET

  1. En Visual Studio, haga clic con el botón derecho en el proyecto de servidor. A continuación, seleccione Administrar paquetes NuGet. Microsoft.Azure.NotificationHubsBusque y, a continuación, seleccione Instalar. Este proceso instala la biblioteca de Notification Hubs para enviar notificaciones desde el back-end.

  2. En el proyecto de servidor, abra Controladores>TodoItemController.cs. A continuación, agregue las siguientes instrucciones using:

    using System.Collections.Generic;
    using Microsoft.Azure.NotificationHubs;
    using Microsoft.Azure.Mobile.Server.Config;
    
  3. En el método PostTodoItem , agregue el código siguiente después de la llamada a InsertAsync:

    // Get the settings for the server project.
    HttpConfiguration config = this.Configuration;
    MobileAppSettingsDictionary settings =
        this.Configuration.GetMobileAppSettingsProvider().GetMobileAppSettings();
    
    // Get the Notification Hubs credentials for the mobile app.
    string notificationHubName = settings.NotificationHubName;
    string notificationHubConnection = settings
        .Connections[MobileAppSettingsKeys.NotificationHubConnectionString].ConnectionString;
    
    // Create a new Notification Hub client.
    NotificationHubClient hub = NotificationHubClient
    .CreateClientFromConnectionString(notificationHubConnection, notificationHubName);
    
    // Send the message so that all template registrations that contain "messageParam"
    // receive the notifications. This includes APNS, GCM, WNS, and MPNS template registrations.
    Dictionary<string,string> templateParams = new Dictionary<string,string>();
    templateParams["messageParam"] = item.Text + " was added to the list.";
    
    try
    {
        // Send the push notification and log the results.
        var result = await hub.SendTemplateNotificationAsync(templateParams);
    
        // Write the success result to the logs.
        config.Services.GetTraceWriter().Info(result.State.ToString());
    }
    catch (System.Exception ex)
    {
        // Write the failure result to the logs.
        config.Services.GetTraceWriter()
            .Error(ex.Message, null, "Push.SendAsync Error");
    }
    

    Este proceso envía una notificación de plantilla que contiene el item.Text cuando se inserta un nuevo elemento.

  4. Vuelva a publicar el proyecto de servidor.

Proyecto de back-end en Node.js

  1. Configure el proyecto de back-end.

  2. Reemplace el código existente en todoitem.js por el código siguiente:

    var azureMobileApps = require('azure-mobile-apps'),
    promises = require('azure-mobile-apps/src/utilities/promises'),
    logger = require('azure-mobile-apps/src/logger');
    
    var table = azureMobileApps.table();
    
    table.insert(function (context) {
    // For more information about the Notification Hubs JavaScript SDK,
    // see https://aka.ms/nodejshubs.
    logger.info('Running TodoItem.insert');
    
    // Define the template payload.
    var payload = '{"messageParam": "' + context.item.text + '" }';  
    
    // Execute the insert. The insert returns the results as a promise.
    // Do the push as a post-execute action within the promise flow.
    return context.execute()
        .then(function (results) {
            // Only do the push if configured.
            if (context.push) {
                // Send a template notification.
                context.push.send(null, payload, function (error) {
                    if (error) {
                        logger.error('Error while sending push notification: ', error);
                    } else {
                        logger.info('Push notification sent successfully!');
                    }
                });
            }
            // Don't forget to return the results from the context.execute().
            return results;
        })
        .catch(function (error) {
            logger.error('Error while running context.execute: ', error);
        });
    });
    
    module.exports = table;  
    

    Este proceso envía una notificación de plantilla que contiene item.text cuando se inserta un nuevo elemento.

  3. Al editar el archivo en el equipo local, vuelva a publicar el proyecto de servidor.

Configuración del proyecto de cliente para notificaciones push

  1. En la vista Solución (o explorador de soluciones en Visual Studio), haga clic con el botón derecho en la carpeta Componentes , haga clic en Obtener más componentes..., busque el componente Google Cloud Messaging Client y agréguelo al proyecto.

  2. Abra el archivo de proyecto ToDoActivity.cs y agregue la siguiente directiva using a la clase:

    using Gcm.Client;
    
  3. En la clase ToDoActivity , agregue el siguiente código nuevo:

    // Create a new instance field for this activity.
    static ToDoActivity instance = new ToDoActivity();
    
    // Return the current activity instance.
    public static ToDoActivity CurrentActivity
    {
        get
        {
            return instance;
        }
    }
    // Return the Mobile Services client.
    public MobileServiceClient CurrentClient
    {
        get
        {
            return client;
        }
    }
    

    Esto le permite acceder a la instancia de cliente móvil desde el proceso del servicio de gestión de notificaciones push.

  4. Agregue el código siguiente al método OnCreate después de crear MobileServiceClient :

    // Set the current instance of TodoActivity.
    instance = this;
    
    // Make sure the GCM client is set up correctly.
    GcmClient.CheckDevice(this);
    GcmClient.CheckManifest(this);
    
    // Register the app for push notifications.
    GcmClient.Register(this, ToDoBroadcastReceiver.senderIDs);
    

ToDoActivity ya está preparado para agregar notificaciones push.

Adición de código de notificaciones push a la aplicación

  1. Cree una nueva clase en el proyecto denominado ToDoBroadcastReceiver.

  2. Agregue las siguientes instrucciones 'using' a la clase ToDoBroadcastReceiver:

    using Gcm.Client;
    using Microsoft.WindowsAzure.MobileServices;
    using Newtonsoft.Json.Linq;
    
  3. Agregue las siguientes solicitudes de permisos entre las instrucciones using y la declaración de espacio de nombres :

    [assembly: Permission(Name = "@PACKAGE_NAME@.permission.C2D_MESSAGE")]
    [assembly: UsesPermission(Name = "@PACKAGE_NAME@.permission.C2D_MESSAGE")]
    [assembly: UsesPermission(Name = "com.google.android.c2dm.permission.RECEIVE")]
    //GET_ACCOUNTS is only needed for android versions 4.0.3 and below
    [assembly: UsesPermission(Name = "android.permission.GET_ACCOUNTS")]
    [assembly: UsesPermission(Name = "android.permission.INTERNET")]
    [assembly: UsesPermission(Name = "android.permission.WAKE_LOCK")]
    
  4. Reemplace la definición de clase ToDoBroadcastReceiver existente por lo siguiente:

    [BroadcastReceiver(Permission = Gcm.Client.Constants.PERMISSION_GCM_INTENTS)]
    [IntentFilter(new string[] { Gcm.Client.Constants.INTENT_FROM_GCM_MESSAGE }, 
        Categories = new string[] { "@PACKAGE_NAME@" })]
    [IntentFilter(new string[] { Gcm.Client.Constants.INTENT_FROM_GCM_REGISTRATION_CALLBACK }, 
        Categories = new string[] { "@PACKAGE_NAME@" })]
    [IntentFilter(new string[] { Gcm.Client.Constants.INTENT_FROM_GCM_LIBRARY_RETRY }, 
    Categories = new string[] { "@PACKAGE_NAME@" })]
    public class ToDoBroadcastReceiver : GcmBroadcastReceiverBase<PushHandlerService>
    {
        // Set the Google app ID.
        public static string[] senderIDs = new string[] { "<PROJECT_NUMBER>" };
    }
    

    En el código anterior, debe reemplazar <PROJECT_NUMBER> por el número de proyecto asignado por Google al aprovisionar la aplicación en el portal para desarrolladores de Google.

  5. En el archivo de proyecto ToDoBroadcastReceiver.cs, agregue el código siguiente que define la clase PushHandlerService:

    // The ServiceAttribute must be applied to the class.
    [Service]
    public class PushHandlerService : GcmServiceBase
    {
        public static string RegistrationID { get; private set; }
        public PushHandlerService() : base(ToDoBroadcastReceiver.senderIDs) { }
    }
    

    Tenga en cuenta que esta clase deriva de GcmServiceBase y que el atributo Service debe aplicarse a esta clase.

    Nota:

    La clase GcmServiceBase implementa los métodos OnRegistered(), OnUnRegistered(), OnMessage() y OnError(). Debe invalidar estos métodos en la clase PushHandlerService .

  6. Agregue el código siguiente a la clase PushHandlerService que invalida el controlador de eventos OnRegistered .

    protected override void OnRegistered(Context context, string registrationId)
    {
        System.Diagnostics.Debug.WriteLine("The device has been registered with GCM.", "Success!");
    
        // Get the MobileServiceClient from the current activity instance.
        MobileServiceClient client = ToDoActivity.CurrentActivity.CurrentClient;
        var push = client.GetPush();
    
        // Define a message body for GCM.
        const string templateBodyGCM = "{\"data\":{\"message\":\"$(messageParam)\"}}";
    
        // Define the template registration as JSON.
        JObject templates = new JObject();
        templates["genericMessage"] = new JObject
        {
            {"body", templateBodyGCM }
        };
    
        try
        {
            // Make sure we run the registration on the same thread as the activity, 
            // to avoid threading errors.
            ToDoActivity.CurrentActivity.RunOnUiThread(
    
                // Register the template with Notification Hubs.
                async () => await push.RegisterAsync(registrationId, templates));
    
            System.Diagnostics.Debug.WriteLine(
                string.Format("Push Installation Id", push.InstallationId.ToString()));
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine(
                string.Format("Error with Azure push registration: {0}", ex.Message));
        }
    }
    

    Este método usa el identificador de registro de GCM devuelto para registrarse en Azure para notificaciones push. Las etiquetas solo se pueden agregar al registro después de crearla. Para obtener más información, consulte Cómo: Agregar etiquetas a la instalación de un dispositivo para habilitar el push-to-tags.

  7. Invalide el método OnMessage en PushHandlerService con el código siguiente:

    protected override void OnMessage(Context context, Intent intent)
    {
        string message = string.Empty;
    
        // Extract the push notification message from the intent.
        if (intent.Extras.ContainsKey("message"))
        {
            message = intent.Extras.Get("message").ToString();
            var title = "New item added:";
    
            // Create a notification manager to send the notification.
            var notificationManager = 
                GetSystemService(Context.NotificationService) as NotificationManager;
    
            // Create a new intent to show the notification in the UI. 
            PendingIntent contentIntent =
                PendingIntent.GetActivity(context, 0,
                new Intent(this, typeof(ToDoActivity)), 0);
    
            // Create the notification using the builder.
            var builder = new Notification.Builder(context);
            builder.SetAutoCancel(true);
            builder.SetContentTitle(title);
            builder.SetContentText(message);
            builder.SetSmallIcon(Resource.Drawable.ic_launcher);
            builder.SetContentIntent(contentIntent);
            var notification = builder.Build();
    
            // Display the notification in the Notifications Area.
            notificationManager.Notify(1, notification);
    
        }
    }
    
  8. Invalide los métodos OnUnRegistered() y OnError() con el código siguiente.

    protected override void OnUnRegistered(Context context, string registrationId)
    {
        throw new NotImplementedException();
    }
    
    protected override void OnError(Context context, string errorId)
    {
        System.Diagnostics.Debug.WriteLine(
            string.Format("Error occurred in the notification: {0}.", errorId));
    }
    

Prueba de las notificaciones push en la aplicación

Puede probar la aplicación mediante un dispositivo virtual en el emulador. Hay pasos de configuración adicionales necesarios al ejecutarse en un emulador.

  1. El dispositivo virtual debe tener las API de Google establecidas como destino en el administrador de dispositivos virtuales Android (AVD).

  2. Agregue una cuenta de Google al dispositivo Android haciendo clic en Aplicaciones>Configuración>Añadir cuenta, y luego siga las indicaciones.

  3. Ejecute la aplicación todolist como antes e inserte un nuevo elemento de tareas pendientes. Esta vez, se muestra un icono de notificación en el área de notificación. Puede abrir el cajón de notificaciones para ver el texto completo de la notificación.