首页 > 解决方案 > FCM如何在通知单击期间从后台打开应用程序时获取Notification().getTitle()

问题描述

当应用程序未运行且用户单击通知时,它将打开初始屏幕,但它 getExtras 没有标题和正文之类的键。但是,如果应用程序正在运行并且从中发送通知MyFirebaseMessagingService,它将打印标题和正文。这里有什么问题?

if (getIntent().getExtras() != null) {
    for (String key : getIntent().getExtras().keySet()) {
        String value = getIntent().getExtras().getString(key);
        switch (key){
            case "body":{
                if(value.contains("order successfully")){
                    orderSuccessfully=true;
                }
                break;
            }
        }
        Log.d("readingNotiMain", "Key: " + key + " Value: " + value+"  vc:"+value.contains("order successfully"));
    }
}



public class MyFirebaseMessagingService extends FirebaseMessagingService {
    private static final String TAG = "MyFirebaseMsgService";

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        Log.d(TAG, "From: " + remoteMessage.getFrom());
/*        // Check if message contains a data payload.
        if (remoteMessage.getData().size() > 0) {
            Log.d(TAG, "Message data payload: " + remoteMessage.getData());
            if (*//* Check if data needs to be processed by long running job *//* true) {
                // For long-running tasks (10 seconds or more) use Firebase Job Dispatcher.
                scheduleJob();
            } else {
                // Handle message within 10 seconds
                handleNow();
            }
        }*/

       // Check if message contains a notification payload.
        if (remoteMessage.getNotification() != null) {

            sendNotification(remoteMessage.getNotification().getTitle(), remoteMessage.getNotification().getBody());

            if(remoteMessage.getData()!=null){

                Log.i(TAG,"data:"+new Gson().toJson(remoteMessage.getData())+"");
                Log.i(TAG,"don "+new Gson().toJson(remoteMessage.getData()));
            }

            Log.d(TAG, "Message Notification title: " + remoteMessage.getNotification().getTitle()
                    +" \n Body"+ remoteMessage.getNotification().getBody());

        }
    }

    @Override
    public void onNewToken(String token) {
        Log.d(TAG, "Refreshed token: " + token);
        sendRegistrationToServer(token);
    }
    // [END on_new_token]

    private void scheduleJob() {
//        // [START dispatch_job]
//        FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(this));
//        Job myJob = dispatcher.newJobBuilder()
//                .setService(MyJobService.class)
//                .setTag("my-job-tag")
//                .build();
//        dispatcher.schedule(myJob);
//        // [END dispatch_job]
    }


    private void handleNow() {
        Log.d(TAG, "Short lived task is done.");
    }


    private void sendRegistrationToServer(String token) {
        // TODO: Implement this method to send token to your app server.
    }


    private void sendNotification(String title,String messageBody) {
        Intent intent = new Intent(this, Main_Act.class);
        intent.putExtra("body",messageBody);
        intent.putExtra("title",title);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
                PendingIntent.FLAG_ONE_SHOT);
        Intent orderPageIntent=new Intent(getApplicationContext(),Main_Act.class);
        String channelId = getString(R.string.default_notification_channel_id);
        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder =
                new NotificationCompat.Builder(this, channelId)
                        .setSmallIcon(R.mipmap.ic_launcher_round)
                        .setContentTitle(getString(R.string.fcm_message))
                        .setContentText(messageBody)
                        .setAutoCancel(true)
                        .setSound(defaultSoundUri)
                        .setContentIntent(pendingIntent);

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        // Since android Oreo notification channel is needed.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(channelId,
                    "ssss",
                    NotificationManager.IMPORTANCE_DEFAULT);
            notificationManager.createNotificationChannel(channel);
        }

        notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
    }
}

标签: firebase-cloud-messaging

解决方案


实际上,在 FCM 中有两种可用的有效负载(消息类型),一种是Data,另一种是Notification,所以如果您使用通知有效负载,那么当应用程序处于后台时,您无法在 onReceive 和前台处理通知,您可以处理它,所以我只是建议如果你想在两种情况下都处理数据,那么只放有效data载荷不要放notification有效载荷

您可以从以下文档中获得更多理解

关于 FCM 消息类型

这是服务器端有效负载示例

带有通知负载

{"to":"[add your token]","notification":{"title":"Working Good","body":"[add your message]"},"priority":"high"}

使用数据负载

{"to":"[add your token]","data":{"title":"Working Good","body":"[add your message]"},"priority":"high"}

推荐阅读