简体   繁体   English

FCM:当应用程序处于前台状态时处理其应用程序的不同数据通知

[英]FCM : Handling different data notification of an android app when app is in foreground

I am sending 2 different data notifications in my app using cloud functions. 我正在使用云功能在我的应用程序中发送2种不同的数据通知。

when I received the 1st notification in app and taps on notification it redirects to the my intended page using pendingIntent. 当我在应用程序中收到第一条通知并点击通知时,它会使用未决Intent重定向到我的预期页面。

Now when I received the 2nd notification in app and taps on notification how to redirects to another activity(sent Invitation page). 现在,当我在应用程序中收到第二条通知并点击通知时,如何重定向到另一个活动(已发送邀请页面)。 How to implement this . 如何实现这一点。

my firebasemessaging class 我的firebasemessaging类

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

import java.util.HashMap;
import java.util.Map;

public class MyFirebaseMessagingService extends FirebaseMessagingService {
    private static final String TAG = "MY android fcm service";
    FirebaseUser firebaseUser;
    FirebaseAuth mAuth;
    FirebaseFirestore db = FirebaseFirestore.getInstance();
      String docId ;

    @Override
    public void onMessageReceived(final RemoteMessage remoteMessage) {
        String FirstName = "0";
        String Amount = "0";
        String SenderID1 = "0";
        String ReceiverId1 ="0";
        String ReceiverPhoneNumberst="0";
        String SenderAutoId="0";


        mAuth = FirebaseAuth.getInstance();
        firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
        if (remoteMessage.getData().size() > 0) {
            Log.d(TAG, "Message data payload: " + remoteMessage.getData());
            FirstName = remoteMessage.getData().get("Name");
            Amount = remoteMessage.getData().get("Amount");
            SenderID1=remoteMessage.getData().get("SenderID");
            System.out.println("Senderid"+SenderID1);
            ReceiverId1=remoteMessage.getData().get("ReceiverId");
            ReceiverPhoneNumberst=remoteMessage.getData().get("ReceiverPhoneNumber");
            long ReceiverPhoneNumber = Long.parseLong(ReceiverPhoneNumberst);
            SenderAutoId=remoteMessage.getData().get("SenderAutoId");
            Map<String,Object> data = new HashMap<>();
            data.put("SenderName",FirstName);
            data.put("Amount",Amount);
            data.put("SenderID",SenderID1);
            data.put("ReceiverId",ReceiverId1);
            data.put("ReceiverPhoneNumber",ReceiverPhoneNumber);
            data.put("SenderAutoId",SenderAutoId);

            final String finalAmount = Amount;
            final String finalFirstName = FirstName;
            db.collection("deyaPayUsers").document(mAuth.getUid().toString()).collection("Split").document(mAuth.getUid().toString()).collection("ReceivedInvitation").add(data).addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
                @Override
                public void onSuccess(DocumentReference documentReference) {

                    docId = documentReference.getId();
                    Log.d(TAG,"DocumentSnapshot written with ID:" +docId);
                    //System.out.println("documentadded is docId"+ docId);

                    Log.d(TAG, "From:" + remoteMessage.getFrom());
                    Log.d(TAG, "Notification MessageBody:" + remoteMessage.getNotification().getBody());
                    Log.d(TAG, "Notification data:" + remoteMessage.getData());
                    createNotification(remoteMessage.getNotification().getBody(), finalFirstName, finalAmount, docId);
                   // createNotification1(remoteMessage.getNotification().getBody());




                }
            }).addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    Log.w(TAG,"Error adding document",e);
                }
            });

        }
    }



    private void createNotification(String messageBody, String FirstName, String amount,String docId) {
        Intent intent = new Intent( this,ReceivedNotification.class );
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra("FirstName",FirstName);
        System.out.println(FirstName);
        intent.putExtra("Amount",amount);
        intent.putExtra("DocumentId",docId);
        System.out.print("dDA "+docId);
        PendingIntent resultIntent = PendingIntent.getActivity( this , 0, intent,
                PendingIntent.FLAG_UPDATE_CURRENT);

        Uri notificationSoundURI = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder mNotificationBuilder = new NotificationCompat.Builder( this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("deyaPay")
                .setContentText(messageBody)
                .setAutoCancel(true )
                .setSound(notificationSoundURI)
                .setContentIntent(resultIntent)
                .setVisibility(Notification.VISIBILITY_PUBLIC);
        //.setSmallIcon(R.drawable.ic_stat_player)
        // Add media control buttons that invoke intents in your media service
        //.addAction(R.drawable.accept, "Accept",) // #0
        //.addAction(R.drawable.ic_reject, "Reject", ResultActivity.class) ; // ;

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

        notificationManager.notify(0, mNotificationBuilder.build());


    }
}

here is the simple snippet use a flag in the notification you push from the server. 这是您从服务器推送的通知中使用标记的简单代码段。

when you receive notification in onMessageRecevied function extract that flag and pass it to sendNotification 当您在onMessageRecevied函数中收到通知时,提取该标志并将其传递给sendNotification

    private void sendNotification(int flag, String title,String messageBody ) {
NotificationManager    mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    long notificatioId = System.currentTimeMillis();


Intent intent=null;
   if(flag==1){
        intent = new Intent(getApplicationContext(), activity1.class);
   }
   else{
         intent = new Intent(getApplicationContext(), activity2.class);
   }

    intent.putExtra("fromItem",false);
    intent.putExtra("title", title);; // Here pass your activity where you want to redirect.

    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
    PendingIntent contentIntent = PendingIntent.getActivity(this, (int) (Math.random() * 100), intent, 0);

    int currentapiVersion = android.os.Build.VERSION.SDK_INT;
    if (currentapiVersion >= android.os.Build.VERSION_CODES.LOLLIPOP){
        currentapiVersion = R.mipmap.ic_launcher;
    } else{
        currentapiVersion = R.mipmap.ic_launcher;
    }

    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(currentapiVersion)
            .setContentTitle(this.getResources().getString(R.string.app_name))
            .setStyle(new NotificationCompat.BigTextStyle().bigText(messageBody))
            .setContentText(title)
            .setAutoCancel(true)
            .setPriority(Notification.PRIORITY_HIGH)
            .setDefaults(Notification.FLAG_AUTO_CANCEL | Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE | Notification.DEFAULT_SOUND)
            .setContentIntent(contentIntent);
    mNotificationManager.notify((int) notificatioId, notificationBuilder.build());
}

In the server side code add the flag in the JSON message 在服务器端代码中,将标志添加到JSON消息中

 var data = new
            {

                to=deviceId,
                    notification = new
                    {
                        body = "\""+notificationMessage +"\"",
                        title = "\""+_title+"\"",
                        sound = "Enabled\""
                    }
                    ,
                    data=new {

                        flag= "\"" + _flag+"\"",
                        message= "\""+notificationMessage+"\"",
                        additional = "\"" + addtional+"\""

                    }




            };

this is the simple snippet for json packet 这是json数据包的简单代码段

You can't predefined it in NotificationBuilder , but you can do one thing you can create one common activity and route all notifications to this activity with some flag/type to recognise the notification type. 您无法在NotificationBuilder预定义它,但是您可以做一件事,创建一个通用活动,并使用某种标记/类型将所有通知路由到该活动,以识别通知类型。 From this activity you can redirect to your desired activity by checking the notification type you passed. 通过检查您传递的通知类型,您可以从此活动重定向到所需的活动。

Inside this function, change Intent according to messageBody, 在此函数内,根据messageBody更改Intent,

private void createNotification(String messageBody, String FirstName, String amount,String docId) {

    Intent intent=null;
    if(messageBody.contains(“xyz”))
            intent = new Intent( this, ReceivedNotification.class );
    else
            intent = new Intent( this, SecondReceivedNotification.class );

    — — —

    PendingIntent resultIntent = PendingIntent.getActivity( this , 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);
}

and pass it over to Pending Intent. 并将其传递给“待处理的意图”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 当应用程序在前台而不是后台时,FCM通知,通知单击 - FCM notification, notification click when app is in foreground not background 应用程序未启动时处理fcm通知 - Handling fcm notification when app not launched 将FCM通知中的Android应用的前一个实例置于前台 - Bring Android app's previous instance to foreground from FCM notification 在前台在后台收到FCM通知时应用崩溃 - App Crashes when receiving FCM Notification on Foreground works on Background 应用程序在前台时无法处理 FCM 通知 - Can't handdle FCM notification when app in foreground 即使app在前台,如何让FCM显示通知? - How to let FCM display notification even when app is in foreground? 当我的应用程序前台服务被终止时,未收到 FCM 通知 - FCM Notification is not received when my app foreground service is killed 当应用程序处于前台时,是否建议使用静默通知(FCM)将数据推送到移动应用程序中? - Is it recommended to use silent notification(FCM) to push data into mobile apps when the app is in Foreground? 当应用程序未运行时,在 Android 手机上接收 FCM 数据通知 - Receive an FCM data notification on Android phone when app is not running 无论应用是后台还是前台,均未收到FCM通知 - FCM notification not received whether the app in background or foreground
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM