FCM:当应用处于前台时处理Android应用的不同数据通知

时间:2018-03-28 16:00:55

标签: android firebase firebase-cloud-messaging google-cloud-functions

我正在使用云功能在我的应用中发送2个不同的数据通知。

当我在应用程序中收到第一个通知并点击通知时,它会使用pendingIntent重定向到我想要的页面。

现在,当我收到应用程序中的第二个通知并点击通知如何重定向到另一个活动时(发送的邀请页面)。如何实现这一点。

我的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());


    }
}

3 个答案:

答案 0 :(得分:2)

这是简单的代码段 在从服务器推送的通知中使用标记。

当您在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());
}

在服务器端代码中添加JSON消息中的标志

 var data = new
            {

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

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

                    }




            };

这是json数据包的简单片段

答案 1 :(得分:1)

您无法在NotificationBuilder中对其进行预定义,但您可以执行以下操作:创建一个公共活动并将所有通知路由到此活动,并使用一些标记/类型来识别通知类型。通过此活动,您可以通过检查您传递的通知类型重定向到所需的活动。

答案 2 :(得分:1)

在此功能中,根据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);
}

并将其传递给Pending Intent。