11

Mes applications reçoivent une notification Push via Firebase. Maintenant, il a 3 situations distinctes qui peuvent se produire lorsque la notification arrive:StatusBarNotification comment obtenir des données ou renvoyer l'intention?

  1. L'application est au premier plan
  2. L'application est en arrière-plan
  3. L'application ne fonctionne pas

Situation 1 n'est pas un problème. La notification est reçue dans l'application ok. Les situations 2 et 3 fonctionnent correctement tant que vous appuyez sur la notification dans le tiroir. Dans les situations 2 et 3, lorsque l'icône de l'application est sélectionnée à la place de l'icône du tiroir, l'application ne reçoit aucune notification. J'ai essayé d'obtenir les notifications actives de StatusBar et cela fonctionne mais je ne peux pas récupérer les données des extras ou renvoyer la notification au service de notification push en attente. Voici le code expérimental pour obtenir les notifications.

 NotificationManager notificationManager = (NotificationManager)Application.Context.GetSystemService(Context.NotificationService); 

     var notifications = notificationManager.GetActiveNotifications() 
      .Where(notif => notif.PackageName == Application.Context.PackageName); 

     foreach (var notification in notifications) 
     { 
      Log.Info(TAG, "OnActivityResumed: Notification in active in Status Bar: {0}", notification.Notification.ToString()); 

      var data = notification.Notification.Extras.GetString("data"); 

      Log.Debug("Notifier", "Data received: {0}", data); 

      //if (data != null) 
      //{ 
      // Settings.Notification = JsonConvert.DeserializeObject<LoginNotificationParameter>(data); 
      //} 
     } 

     // Canceling all notifications 
     notificationManager.CancelAll(); 

Questions:

  1. Est-il exact que le comportement de l'application ne reçoit aucune intentions lorsqu'une notification est dans le tiroir?
  2. Si oui, comment gérer les situations 2 et 3 lorsque l'utilisateur appuie sur l'icône de l'application au lieu de la notification du tiroir?

Je vois ces données dans la notification de het lors de l'impression de tous les extras Valeurs clés:

06-28 16:34:13.174 20792 20792 I Notifier: OnActivityResumed: Notification is active in Status Bar: Notification(pri=0 contentView=null vibrate=null sound=content://settings/system/notification_sound defaults=0x0 flags=0x10 color=0x00000000 vis=PRIVATE semFlags=0x0 semPriority=0) 
06-28 16:34:13.191 20792 20792 I Notifier: KeyIn: Extras Key: android.title Data: Login 
06-28 16:34:13.191 20792 20792 I Notifier: KeyIn: Extras Key: android.subText Data: 
06-28 16:34:13.191 20792 20792 I Notifier: KeyIn: Extras Key: android.template Data: android.app.Notification$BigTextStyle 
06-28 16:34:13.192 20792 20792 I Notifier: KeyIn: Extras Key: android.showChronometer Data: false 
06-28 16:34:13.192 20792 20792 I Notifier: KeyIn: Extras Key: android.text Data: Er is een inlogverzoek voor u ontvangen. 
06-28 16:34:13.194 20792 20792 I Notifier: KeyIn: Extras Key: android.progress Data: 0 
06-28 16:34:13.194 20792 20792 I Notifier: KeyIn: Extras Key: android.progressMax Data: 0 
06-28 16:34:13.195 20792 20792 I Notifier: KeyIn: Extras Key: android.appInfo Data: ApplicationInfo{a27f281 nl.natuurnetwerk.notifier} 
06-28 16:34:13.195 20792 20792 I Notifier: KeyIn: Extras Key: android.showWhen Data: true 
06-28 16:34:13.195 20792 20792 I Notifier: KeyIn: Extras Key: android.largeIcon Data: 
06-28 16:34:13.195 20792 20792 I Notifier: KeyIn: Extras Key: android.bigText Data: Er is een inlogverzoek voor u ontvangen. 
06-28 16:34:13.195 20792 20792 I Notifier: KeyIn: Extras Key: android.infoText Data: 
06-28 16:34:13.195 20792 20792 I Notifier: KeyIn: Extras Key: android.originatingUserId Data: 0 
06-28 16:34:13.196 20792 20792 I Notifier: KeyIn: Extras Key: android.progressIndeterminate Data: false 
06-28 16:34:13.196 20792 20792 I Notifier: KeyIn: Extras Key: android.remoteInputHistory Data: 
+0

Vous souhaitez mettre à jour les données de votre application avec la notification? – apineda

+0

La fonction de l'application est de vérifier une connexion à partir d'un site Web. Lorsqu'un utilisateur se connecte à un site Web spécifique avec UserId/Password, une notificationn est envoyée à l'application. Lorsque l'application s'ouvre, elle commence à rechercher un code QR qui s'affiche après la connexion sur le site Web. Les informations dans la notification doivent être égales aux informations contenues dans le code QR. Lorsque cela correspond au site Web continue à sa page d'accueil. Sinon, la connexion est refusée. –

Répondre

7

Ok, cela fonctionne pour moi tous les Etats app que je peux penser:

using Android.App; 
using Android.Content; 
using Android.OS; 
using MvvmCross.Droid.Platform; 
using MvvmCross.Droid.Support.V4; 

namespace Notifier.Android.Classes.Services 
{ 
    /// <summary> 
    /// This class receives all Firebase intents. 
    /// </summary> 
    [BroadcastReceiver(Enabled = true, Permission = "com.google.android.c2dm.permission.SEND")] 
    [IntentFilter(new[] { "com.google.android.c2dm.intent.RECEIVE" }, Categories = new string[] { "com.yourdomain.yourapp" })] 
    public class FirebaseBroadcastReceiver : MvxWakefulBroadcastReceiver 
    { 
     public override void OnReceive(Context context, Intent intent) 
     { 
      var setup = MvxAndroidSetupSingleton.EnsureSingletonAvailable(context); 
      setup.EnsureInitialized(); 

      var service = new Intent(context, typeof(FirebaseBroadcastReceiver)); 

      PowerManager.WakeLock sWakeLock; 
      var pm = PowerManager.FromContext(context); 
      sWakeLock = pm.NewWakeLock(WakeLockFlags.Full, "FirebaseBroadcastReceiver"); 
      sWakeLock.Acquire(); 


      if (intent.Extras != null) 
      { 
       // Your code to handle the intent 
      } 

      sWakeLock.Release(); 

      StartWakefulService(context, service); 
     } 
    } 
} 
1

J'ai essayé ceci:

private void HandlePendingNotifications() 
    { 
     NotificationManager notificationManager = (NotificationManager)Application.Context.GetSystemService(Context.NotificationService); 

     var notifications = notificationManager.GetActiveNotifications() 
      .OrderByDescending(notif => notif.PostTime) 
      .Where(notif => notif.PackageName == Application.Context.PackageName); 

     var notification = notifications.FirstOrDefault(); 

     if (notification != null) 
     { 
      Log.Debug(TAG, "OnActivityResumed: Notification is active in Status Bar: {0}", notification.Notification.ToString()); 

      NotificationManagerCompat nm = NotificationManagerCompat.From(this); 

      notification.Notification.Sound = null; 
      notification.Notification.Vibrate = null; 

      // nm.Cancel(notification.Id); 
      nm.Notify(0, notification.Notification); 
     } 

     //Timer timer = new Timer((state) => 
     //{ 
     // // Canceling all notifications 
     // notificationManager.CancelAll(); 
     // timer = null; 
     //}, null, 2000, 2000); 
    } 

Mais pour une raison quelconque la notification est envoyée, mais n'arrive jamais à mon application.

+0

La notification nouvellement envoyée est affichée dans le tiroir, mais en appuyant dessus, elle n'active pas mon application. –

+0

Après Notify() il y a 2 notifications dans le tiroir. L'original et celui que j'ai envoyé. L'original active mon application. Le second ne le fait pas. –

1

Prolonge FirebaseMessagingService et passer outre les callbacks onMessageReceived et onDeletedMessages. Pour ouvrir automatiquement une application/activité lors de la réception d'une notification, vous devez utiliser un attribut data (quelque chose comme {"data" : { "some_key" : "some_value"}}) dans votre charge, ce qui garantit d'invoquer toujours la méthode FirebaseMessagingService.onMessageReceived().

Veuillez noter que l'ouverture d'une activité/application sur une notification sans interaction de l'utilisateur est vraiment mauvaise et devrait être évitée.

+0

@Paul Sinnema: Ma réponse est pour Android, vous ajustez la réponse avec des classes équivalentes disponibles dans Xamarin. –

+0

C'est exactement comme ça que je l'ai implémenté. Le problème était que lorsque l'application est en arrière-plan et que l'utilisateur appuie sur l'icône à la place de la notification du bac, aucune notification n'est reçue et nous devrions la récupérer nous-mêmes. Le WakefulBroadcastReceiver comme indiqué dans ma propre réponse résout ce problème très bien. –