Firebase-无法设置标题和通知消息

时间:2018-06-29 10:37:53

标签: android firebase firebase-cloud-messaging

我从PHP服务器将此通知数据发送到Firebase API:

$fields = [
    'to' => "fcm....",
    'notification' => [
        'title' => 'Test Test Test',
        'body' => 'MSG MSG MSG'
    ],
    'data' => [
        'type' => 'message',
        'sender' => 'someone'
    ],
    'priority' => 'high'
];

在android studio中,这是MyFirebaseMessagingService类,它扩展了FirebaseMessagingService类:

public class MyFirebaseMessagingService extends FirebaseMessagingService {
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        sendNotification("Test", "Test");
    }

    private void sendNotification(String title, String message) {
        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
                PendingIntent.FLAG_ONE_SHOT);

        String channelId = getString(R.string.notification_channel_id);
        Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder =
                new NotificationCompat.Builder(this, channelId)
                        .setSmallIcon(R.drawable.notificatino)
                        .setContentTitle(title)
                        .setContentText(message)
                        .setAutoCancel(true)
                        .setSound(defaultSoundUri)
                        .setContentIntent(pendingIntent);

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

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(channelId,
                    "Channel human readable title",
                    NotificationManager.IMPORTANCE_DEFAULT);
            notificationManager.createNotificationChannel(channel);
        }

        notificationManager.notify(0, notificationBuilder.build());
    }
}

问题是我保留从服务器获取带有标题和消息的通知(标题标题,MSG MSG MSG),而不是从带有我作为参数传递给sendNotification的标题和消息的获取通知:

The notification I receive not including the title and message I have passed to the function

1 个答案:

答案 0 :(得分:1)

您是否已将MyFirebaseMessagingService添加到AndroidManifest.xml文件中,如下所示:

<service android:name=".firebase.messaging.MyFirebaseMessagingService">
      <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
      </intent-filter>
</service>

还要考虑到,如果应用程序关闭(被杀死或处于非活动状态),则不会调用该类,您将需要从服务器正确发送消息数据。