android - 推送通知不适用于 FCM

标签 android firebase notifications firebase-cloud-messaging

我正尝试在我的 Android 应用程序中使用 Firebase 获取推送通知。问题是当应用程序在前台时,我收到通知并调用 onMessageReceived(),但是当我在后台时,我没有收到任何通知并且 onMessageRecieved 未被调用。

我做错了什么?

list .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());

    }
}

最佳答案

想通了。这是 Firebase SDK 处理服务器响应的方式的问题。我在服务器端使用“通知”字段发送通知。

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

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

在服务器端,我是这样做的:

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

Further Info

关于android - 推送通知不适用于 FCM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40092465/

相关文章:

android - 如何使用房间数据库获取表的最后一条记录

具有多个值的 Firebase 数据库过滤

angular - 在 Angular 中将异步数据从父级传递给子级

azure - 如何在 Xamarin UWP 应用中检索 Toast 通知消息?

php - 如何将特定用户的通知标记为已读并在 laravel 5 中发布?

android - 如何对像whatsapp这样的android通知进行分组?

android - Sygic 不显示当前位置也不显示标记

android - 在 list 中注册应用程序类?

android - 适用于Android Studio 2.3.3的Gradle v4.3.1

php - 使用 PHP 的 Firebase 推送通知