且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

推送通知不与FCM一起使用

更新时间:2023-09-19 10:35:04

算出来了。这是由Firebase SDK处理服务器响应的问题。我通过服务器端的通知字段发送通知。

通知 =只在应用程序处于前台时显示通知。这是Firebase SDK / GCM SDK的规则


$ b 数据 =当应用程序处于后台时显示通知。这是Firebase SDK / GCM SDK的规则。

在服务器端,我这样做了:

  body:JSON.stringify({
notification:{
data:{
title:message
},
to :'/ topics / user _'+ username

更多信息


I am trying to get push notifications using Firebase in my Android app. The problem is when the app is in the foreground, I receive the notification and onMessageReceived() is called, however when I am on the background, I don't receive any notification and the onMessageRecieved isn't called.

What am I doing wrong?

Manifest.xml

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

MyFirebaseMessagingService.class

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    @Override
    public void onCreate() {
        super.onCreate();
        Log.e("MessagingService", "onCreate Firebase Service");
    }

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        Log.e("MessagingService", "onMessageRecieved");

        String body     = remoteMessage.getData().get("body");

        ooVooSdkSampleShowApp application = (ooVooSdkSampleShowApp) getApplication();

        Intent intent = new Intent(application.getContext(), MainActivity.class);
        PendingIntent contentIntent = PendingIntent.getActivity(application.getContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

        NotificationCompat.Builder b = new NotificationCompat.Builder(application.getContext());

        b.setAutoCancel(false)
                .setDefaults(Notification.DEFAULT_ALL)
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.drawable.image_calendar_red)
                .setContentText(body)
                .setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_SOUND)
                .setContentIntent(contentIntent)
                .setContentInfo("Info");

        NotificationManager notificationManager = (NotificationManager) application.getContext().getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(1, b.build());

    }
}

Figured it out. It was the problem with the way server response being handled by Firebase SDK. I was sending notification using "notification" field from the server side.

Notification = Just show Notification when the app is in foreground. This is the rule for Firebase SDK/ GCM SDK

Data = Show Notification when the app is in background. This is the rule for Firebase SDK/GCM SDK.

On server side, I have done it like this:

body: JSON.stringify({
            notification: {
            data: {
                 title: message
             },
             to : '/topics/user_'+username

Further Info

推荐文章