android - 实时数据库值更改后接收推送通知

标签 android firebase firebase-realtime-database push-notification firebase-cloud-messaging

每当节点更新到 FCM 实时数据库时,我想向用户发送推送通知。我的 FCM 功能触发通知。我可以在 FCM 日志中看到这一点。但我无法看到在我的客户端应用程序中显示的通知。有人能帮我吗? enter image description here 我的日志如下: enter image description here

在客户端,我有以下代码来接收通知: MainActivity.java

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

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

        String channelId = "1";
        String channel2 = "2";

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            NotificationChannel notificationChannel = new NotificationChannel(channelId,
                    "Channel 1",NotificationManager.IMPORTANCE_HIGH);

            notificationChannel.setDescription("This is BNT");
            notificationChannel.setLightColor(Color.RED);
            notificationChannel.enableVibration(true);
            notificationChannel.setShowBadge(true);
            notificationManager.createNotificationChannel(notificationChannel);

            NotificationChannel notificationChannel2 = new NotificationChannel(channel2,
                    "Channel 2",NotificationManager.IMPORTANCE_MIN);

            notificationChannel.setDescription("This is bTV");
            notificationChannel.setLightColor(Color.RED);
            notificationChannel.enableVibration(true);
            notificationChannel.setShowBadge(true);
            notificationManager.createNotificationChannel(notificationChannel2);

        }

        // Get Firebase database reference
        this.mDatabase = FirebaseDatabase.getInstance().getReference().child("masterSheet");
        //FirebaseMessaging.getInstance().subscribeToTopic("pushNotifications");
        //FirebaseMessaging.getInstance().subscribeToTopic("pushNotifications");
        // Init user list
        ListView list = (ListView) this.findViewById(R.id.dataList);
        this.listAdapter = new DataListAdapter(this, R.layout.list_view_cell);
        list.setAdapter(listAdapter);
    }

MyFirebaseMessagingService.java

public void onMessageReceived(RemoteMessage remoteMessage) {
    Intent notificationIntent = new Intent(this, MainActivity.class);
    if(MainActivity.isAppRunning){
        //Some action
    }else{
        //Show notification as usual
    }

    notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

    final PendingIntent pendingIntent = PendingIntent.getActivity(this,
            0 /* Request code */, notificationIntent,
            PendingIntent.FLAG_ONE_SHOT);

    //You should use an actual ID instead
    int notificationId = new Random().nextInt(60000);


    Bitmap bitmap = getBitmapfromUrl(remoteMessage.getData().get("image-url"));

    Intent likeIntent = new Intent(this,LikeService.class);
    likeIntent.putExtra(NOTIFICATION_ID_EXTRA,notificationId);
    likeIntent.putExtra(IMAGE_URL_EXTRA,remoteMessage.getData().get("image-url"));
    PendingIntent likePendingIntent = PendingIntent.getService(this,
            notificationId+1,likeIntent,PendingIntent.FLAG_ONE_SHOT);


    Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

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

    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
        setupChannels();
    }

    NotificationCompat.Builder notificationBuilder =
            new NotificationCompat.Builder(this, ADMIN_CHANNEL_ID)
                    .setLargeIcon(bitmap)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle(remoteMessage.getData().get("title"))
                    .setStyle(new NotificationCompat.BigPictureStyle()
                            .setSummaryText(remoteMessage.getData().get("message"))
                            .bigPicture(bitmap))/*Notification with Image*/
                    .setContentText(remoteMessage.getData().get("message"))
                    .setAutoCancel(true)
                    .setSound(defaultSoundUri)
                    .addAction(R.drawable.ic_favorite_true,
                            getString(R.string.notification_add_to_cart_button),likePendingIntent)
                    .setContentIntent(pendingIntent);

    notificationManager.notify(notificationId, notificationBuilder.build());

}

Node.js

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.pushNotification = functions.database.ref('/masterSheet/{pushId}').onWrite( event => {
console.log('Push notification event triggered');
    const payload = {
        notification: {
            title: 'App Name',
            body: "New message",
            sound: "default"
        },
        data: {
            title: "New Title",
            message:"New message"
        }
    };
    const options = {
        priority: "high",
        timeToLive: 60 * 60 * 24 //24 hours
    };
return admin.messaging().sendToTopic("notifications", payload, options);
});

最佳答案

您似乎没有订阅主题“通知”:

FirebaseMessaging.getInstance().subscribeToTopic("notifications");

关于android - 实时数据库值更改后接收推送通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49818006/

相关文章:

android - 使用绘图缓存为 WebView 设置动画。我这样做对吗?

Android fragment popBackStack 和替换不删除 View

java.lang.NullPointerException 和未知来源

node.js - 通过 Firebase 在 Google Cloud 中签名错误

firebase - Firebase:激活只读和非实时模式以提高浏览器性能

Firebase + React Native : Offline authentication

android - Gradle 项目同步失败,原因 : org/gradle/api/internal/FeaturePreviews

firebase - Flutter中的定时支持聊天

AngularFire - Firestore - 在执行查询时检查文档是否存在

android - 应用程序使用混淆器崩溃