托盘图标上未显示Firebase通知消息?

时间:2017-07-26 06:45:18

标签: android firebase firebase-cloud-messaging

我使用this example将Firebase云消息传递与我的应用集成。 通过Firebase控制台发送消息,包括目标用户段主题(主题为新闻)。我的应用程序将显示包含该消息的Toast。

我想要的是通知消息,它将自动显示在Android通知托盘中,而不是吐司。阅读FCM concept后,我尝试了curl:

curl -H "Content-type: application/json" -H "Authorization:key=AAAA....ahjkdkhajksd"  -X POST -d '{ "to": "/topics/news", "notification": { "body":"foo", "title":"bar", "icon":""}}' https://fcm.googleapis.com/fcm/send

虽然通过Toast显示,但不是Android通知托盘。这可能有什么问题?

1 个答案:

答案 0 :(得分:-1)

如果您的应用位于前台,通知栏不会自动显示通知。如果您希望应用显示通知,即使您的应用位于前台,也需要添加以下代码。

<强> MyFirebaseMessagingService.java

public class MyFirebaseMessagingService extends FirebaseMessagingService {

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    JSONObject object = new JSONObject(remoteMessage.getData());
    try {
        String title = object.getString("title");
        String message = object.getString("message");

        Intent intent = new Intent(getBaseContext(), MainActivity.class);
        PendingIntent contentIntent = PendingIntent.getActivity(getBaseContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

        NotificationCompat.Builder b = new NotificationCompat.Builder(getBaseContext());

        b.setAutoCancel(true)
                .setDefaults(Notification.DEFAULT_ALL)
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.drawable.ic_launcher)
                .setTicker("Ticker")
                .setContentTitle(title)
                .setContentText(message)
                .setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_SOUND)
                .setContentIntent(contentIntent)
                .setContentInfo("Info");

        Random r = new Random();
        int randomNo = r.nextInt(100000000 + 1);

        NotificationManager notificationManager = (NotificationManager) getBaseContext().getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(randomNo, b.build());
    } catch (JSONException e) {
        e.printStackTrace();
    }
    super.onMessageReceived(remoteMessage);
}
}