繁体   English   中英

firebase通知处理数据消息背景

[英]firebase Notifications handle Data message Background

在此处输入图片说明在此处输入图片说明

当我的应用程序处于后台(被杀死或暂停到后台)或onMessageReceived回调时,可以发送通知数据消息。

是。 可以做到的。 查看参考Firebase Notification Github Repo

推送通知将基于两件事触发

  • 发送到特定设备(基于fcm令牌)
  • 发送到设备组(基于订阅的主题)

如果设备中收到消息,则将调用onMessageReceived(RemoteMessage remoteMessage)

可以访问远程消息并根据需要和要求执行操作

我会尽量简化初始开发

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    // Do nothing if message is null
    if (remoteMessage == null) return;

    // Data exists
    if (remoteMessage.getData().size() > 0) {
        // To show the notification pass the entire remote message as string 
        sendNotification(remoteMessage.getData().toString());

        // if you've JSON string then decode and handle accordingly
        // Sample
        /**
            try {
                JSONObject json = new JSONObject(remoteMessage.getData().toString());
                sendNotification(JSONObject json); // Need to add method to the class to handle this
            } catch (Exception e) {
                Log.e(TAG, "Exception: " + e.getMessage());
            }           

        */
    }

    /**
     * Create and show a simple notification containing the received FCM message.
     * @param messageBody FCM message body received.
     */
    private void sendNotification(String messageBody) {
        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
                PendingIntent.FLAG_ONE_SHOT);

        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.drawable.ic_stat_ic_notification)
                .setContentTitle("FCM Message")
                .setContentText(messageBody)
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);

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

        notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM