FCM如何在通知单击期间从后台打开应用程序时获取Notification()。getTitle()

时间:2019-11-18 07:17:31

标签: firebase-cloud-messaging

当应用未运行且用户单击通知时,它将打开初始屏幕,但它获取其他内容,没有标题和正文之类的键。但是,如果应用正在运行并且从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());
    }
}

2 个答案:

答案 0 :(得分:0)

实际上,在FCM中,有两种有效负载(消息类型)可用,一种是Data,另一种是Notification,因此,如果您使用的是通知有效负载那么当应用程序在后台运行时,您无法在onReceive中处理通知,而在前台则可以处理它,因此,我只建议您是否要在两种情况下都处理数据,则仅放置data有效负载,不要放置{{ 1}}有效载荷

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

About FCM messages Types

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

具有通知有效负载

notification

具有数据有效负载

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

答案 1 :(得分:-1)

尝试

@Override
public void onMessageReceived (RemoteMessage remoteMessage) {
        super.onMessageReceived (remoteMessage);
}

这个

Map<String, String> data_notify= remoteMessage.getNotification().getBody()

Map<String, String> data_notify= remoteMessage.getData().get("body")

Map<String, String> data_notify =remoteMessage.getData()

只有三种方法可以从RemoteMessage获取数据