我正在从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
...
}
解决方案,如相关问题的答案:How to handle notification when app in background in Firebase,可以在Messages with both notification and data payloads部分的文档中找到,该部分说:
接收包含通知和数据有效负载的消息时的应用程序行为取决于应用程序是在后台还是前台 - 实质上是否在接收时是否处于活动状态。
- 在后台,应用程序在通知托盘中接收通知有效负载,并仅在用户点击通知时处理数据有效负载。
- 在前台时,您的应用会收到一个消息对象,其中包含两个可用的有效负载。
这似乎对我有用YMMV
{
"notification": {
"title": "notification_title",
"body": "notification_body",
"sound": "default"
},
"to" : "device....id"
}
虽然如果背景虽然接受了答案,但这不会唤醒您的应用。