在 android 后台从 firebase 发送通知时没有通知声音、振动和灯光

No notification sound and vibrate and lights when sending notification from firebase in android background

我正在从 firebase 向我的 Android 应用程序发送推送通知。但是当我的应用程序处于后台时,不会调用 firebase onMessageReceived 方法,而是 firebase 向系统发送通知以在系统托盘中显示通知。通知出现在系统托盘中,但没有通知声音,即使我在系统设置中允许我的应用程序发出通知声音。 这是我的通知代码 谢谢

    private void sendNotification(String msg, String title) {
    NotificationManager mNotificationManager = (NotificationManager)
            this.getSystemService(Context.NOTIFICATION_SERVICE);

    PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
            new Intent(this, MainActivity.class), 0);
    Intent i = new Intent(this,MainActivity.class);
    i.putExtra("","");

    NotificationCompat.Builder mBuilder =
            new NotificationCompat.Builder(this)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle(title)
                    .setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
                    .setContentText(msg);
    //Vibration
    mBuilder.setVibrate(new long[] { 200, 400, 600, 800, 1000 });

    //LED
    mBuilder.setLights(Color.MAGENTA, 1000, 1000);

    //Ton
    mBuilder.setSound(Uri.parse("android.resource://"
            + getApplicationContext().getPackageName() + "/" + R.raw.circles_notif));
    mBuilder.setContentIntent(contentIntent);
    mNotificationManager.notify(0, mBuilder.build());
}

从您的 firebase 控制台转到通知 > 新消息 > 高级选项,并将通知作为自定义数据发送。使用 'title' 和 'body' 作为 Key 并按照您想要在通知中显示的方式放置它们的值。当您的应用程序处于后台或被终止时,这应该调用 onMessageReceived()。

如果您从自己的服务器发送通知,这里有一个示例 json 部分:

{   
    "data": {
      "title": "notification_title",
      "body": "notification_body"
    },
    "to" : "jh578_gsh....jhHGFJ76FH"
}

写在override sample of onMessageReceived(),第二个注释行说:

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    ...
    Not getting messages here? See why this may be: ...goo.gl/39bRNJ
    ...
}

comment-link

解决方案,例如相关问题的答案:, can be found in the documentation in Messages with both notification and data payloads 部分说:

App behavior when receiving messages that include both notification and data payloads depends on whether the app is in the background or the foreground—essentially, whether or not it is active at the time of receipt.

  • When in the background, apps receive the notification payload in the notification tray, and only handle the data payload when the user taps on the notification.
  • When in the foreground, your app receives a message object with both payloads available.

这似乎对我有用 YMMV

{
    "notification": {
        "title": "notification_title",
        "body": "notification_body",
        "sound": "default"
    },
    "to" : "device....id"
}

虽然此不会在后台唤醒您的应用程序,但已接受的答案会。