3

J'ai basculé vers l'utilisation de FCM pour mon application. Lorsque mon application est ouverte, je gère les messages manuellement et si le Fragment qui contient la liste des messages n'est pas affiché, alors le code affiche un Notification. Pour afficher la Notification utiliser la fonction:Remplacer la notification FCM par notification créée par programme

public void notify(int id, Notification notification) 

Le problème que je rencontrais est si ma demande est en arrière-plan, FCM affiche une Notification. J'ai même mis le paramètre tag sur le serveur de sorte qu'un seul Notification sera affiché pour l'application. Si l'utilisateur ouvre l'application sans cliquer sur le Notification, puis reçoit un message, un Notification distinct est affiché, ce qui n'est pas ce que je veux. Je suis passé à l'aide de la fonction:

public void notify(String tag, int id, Notification notification) 

Et en utilisant le même tag que le serveur utilise pour le message FCM produit encore une deuxième notification. Y at-il un moyen le Notification je crée par programme peut remplacer le Notification créé par FCM?

Répondre

0

C'est parce que vous recevez des messages de notification de la FCM:

messages de notification sont envoyés vers le bac de notification lorsque l'application est en arrière-plan. Pour les applications au premier plan, les messages sont traités par ces callbacks:

didReceiveRemoteNotification: sur iOS
onMessageReceived() sur Android.

Vous devriez recevoir FCM messages de données au lieu et créer la notification programatically:

application client est responsable du traitement des messages de données.

Documentation

1

S'il vous plaît être conscient que gère la FCM avec des messages purs Notification ou Data des charges utiles différemment. Veuillez vérifier votre message pour voir quel type vous envoyez et vérifier la documentation de Firebase.

J'ai eu la question de quand j'avais une certaine activité en cours d'exécution que je ne voulais pas recevoir une notification. J'ai donc créé une classe d'utilitaire statique qui gardait une propriété booléenne indiquant si cette activité était active. Dans mon récepteur de notification, je vérifie cette valeur et émet la notification ou non. Comme ceci:

Ma classe statique utilitaire:

public class MyRunningActivity { 

    private static boolean isActivityRunning = false; 

    public static void setIsRunningActivity(boolean isRunning){ 
     isActivityRunning = isRunning; 
    } 

    public static boolean getIsRunningActivity(){ 
     return isActivityRunning; 
    } 
} 

Au sein de la classe qui reçoit le onMessageReceived:

@Override 
    public void onMessageReceived(RemoteMessage remoteMessage) { 
     String notification = ""; 
     String title = ""; 
     // Check if message contains a data payload. 
     if (remoteMessage.getData().size() > 0) { 
      title = getDataWithKey(remoteMessage.getData(), "title"); 
      notification = getDataWithKey(remoteMessage.getData(), "body"); 
     } 

     // Check if message contains a notification payload. 
     if (remoteMessage.getNotification() != null) { 
      notification = remoteMessage.getNotification().getBody(); 
      title = remoteMessage.getNotification().getTitle(); 
     } 

     sendNotification(title, notification); 
    } 


private void sendNotification(String notificationTitle, String notificationBody) { 
    try{ 

     Intent intent = new Intent(this, MyActivity.class); 
     intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED | Intent.FLAG_ACTIVITY_NO_ANIMATION); 

     //Generate a new 'unique' request code -- this helps to refresh the activity if it is already active 
     int requestCode = CodeGenerator.getRandomNumber(10, 10000); 

     PendingIntent pendingIntent = null; 

     // If the Activity is active then this will keep the notification from being sent 
     // But the intent Extras will be delivered to the OnNewIntent method and handled there. 
     // I had to put the singleTop flag in the Manifest, otherwise this will cause the 
     // activity to close and reopen.... 
     try { 
      if(MyRunningActivityUtility.getIsRunningActivity()) { 
        intent.putExtra("add_ring_tone","true"); 
        pendingIntent = PendingIntent.getActivity(this, 
               requestCode, 
               intent, 
               PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT 
        ); 

        pendingIntent.send(); 
        \\ !!! Notice that return here prevents the Notification from being sent !!! 
        return; 
       } 
      } 
     } 
     catch (Exception ex1){ 
      Log.e(TAG, ex1.getMessage()); 
     } 

     pendingIntent = PendingIntent.getActivity(this, 
            requestCode, 
            intent, 
            PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT 
     ); 


     Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); 
     NotificationCompat.Builder notificationBuilder = (android.support.v7.app.NotificationCompat.Builder) 
       new NotificationCompat.Builder(this) 
         .setSmallIcon(R.mipmap.your_custom_icon) 
         .setContentTitle(notificationTitle) 
         .setContentText(notificationBody) 
         .setAutoCancel(true) 
         .setSound(defaultSoundUri) 
         .setContentIntent(pendingIntent) 

     NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 

     int idNot = CodeGenerator.getRandomNumber(10, 10000); 
     notificationManager.notify(idNot, notificationBuilder.build()); 
    } 
    catch (Exception ex){ 
     Log.e(TAG, ex.getMessage()); 
    } 
} 

Il pourrait y avoir certaines choses dans cet exemple, vous n'avez pas besoin.