Implemente un método en una app Xamarin.Android
para que al agregar un documento nuevo a una colección en especifica de Firebase Firestore
(si la app esta abierta o en background) envié una notificación local en el dispositivo del cliente correspondiente con un Listener de Firestore
.
Les comparto lo que he logrado:
De este modo (Listener):
vListener = database.Collection("Usuarios")
.Document(IdDocUsuario)
.Collection("Notificaciones")
.OrderBy("FechaHora", Query.Direction.Descending)
.Limit(11)
.AddSnapshotListener(MetadataChanges.Include, this);
Cuando se gatilla el evento (Cuando el Listener detecta un nuevo doc en la coleccion de Firestore):
public void OnEvent(Java.Lang.Object value, FirebaseFirestoreException error)
{
try
{
var data = (QuerySnapshot)value;
if (data == null || data.Metadata.IsFromCache)
{
return;
}
var snapshot = (QuerySnapshot)data;
var Identifier = snapshot.Query.ToString();
//Validaciones propias de la app para no repetir la notificacion, tiempo y demas.
//Notificacion local:
string titulo, cuerpo;
titulo = "Notificacion";
cuerpo = "Hay actividad nueva...";
CrearNotificacionLocal(titulo, cuerpo);
}
catch (Exception Ex)
{
string LineErrorNumber = "Error en linea: " + Ex.StackTrace.Substring(Ex.StackTrace.Length - 7, 7) + "\r\n" + "Error: " + Ex.Message; Crashes.TrackError(Ex);
}
}
Metodo que lanza la notificacion localmente en la barra de notificaciones del telefono:
public int CrearNotificacionLocal(string pTitle, string pBody)
{
try
{ //Configuracion general de notificacion...
if (!channelInitialized)
{
CreateNotificationChannel();
}
messageId++;
//Intent intent = new Intent(AndroidApp.Context, typeof(MainActivity));
Intent intent = new Intent(AndroidApp.Context, typeof(cNotificaciones));
intent.PutExtra(TitleKey, pTitle);
intent.PutExtra(MessageKey, pBody);
intent.AddFlags(ActivityFlags.ClearTop);
PendingIntent pendingIntent = PendingIntent.GetActivity(AndroidApp.Context, pendingIntentId, intent, PendingIntentFlags.UpdateCurrent);
NotificationCompat.Builder builder = new NotificationCompat.Builder(AndroidApp.Context, channelId)
.SetContentIntent(pendingIntent)
.SetContentTitle(pTitle)
.SetContentText(pBody)
.SetAutoCancel(true)
//.SetLargeIcon(BitmapFactory.DecodeResource(AndroidApp.Context.Resources, Resource.Mipmap.Icono3))
.SetSmallIcon(Resource.Mipmap.Icono3)
.SetDefaults((int)NotificationDefaults.Sound | (int)NotificationDefaults.Vibrate);
var notification = builder.Build();
manager.Notify(messageId, notification);
//return messageId;
}
catch (Exception Ex)
{
string LineErrorNumber = "Error en linea: " + Ex.StackTrace.Substring(Ex.StackTrace.Length - 7, 7) + "\r\n" + "Error: " + Ex.Message; Crashes.TrackError(Ex);
//ShowToast("Error en linea: " + LineErrorNumber + "\r\n" + "Error: " + Ex.Message, false);
}
return messageId;
}
Todo bien con esto, el punto es que necesito que también lo haga cuando la app esta cerrada, lei que puedo lograrlo con Cloud Messaging, pero los videos que me encuentro solo sale la opción de Crear una nueva Campaña desde la Consola de Firebase, escribir el titulo, y el cuerpo y definir el target y enviarlo, y yo necesito algo mas "automático".
¿Algún tuto que puedan compartir para hacer esto con Xamarin
? Cualquier info servirá. Gracias.