使用數據對象發送要查看的通知。您可以基本上將所需的所有內容放在數據對象中,並始終通過onMessageReceived
方法接收它。這是一個例子。
public class AppFireBaseMessagingService extends FirebaseMessagingService {
private final static int REQUEST_CODE = 1;
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Map<String, String> data = remoteMessage.getData();
if (data == null) return;
if (data.containsKey("title") && data.containsKey("message")) {
showNotification(data.get("title"), data.get("message"));
}
}
private void showNotification(String title, String body) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setContentTitle(title)
.setSmallIcon(R.drawable.notification_icon);
if (body != null && !body.isEmpty()) {
builder.setStyle(new NotificationCompat.BigTextStyle().bigText(body));
builder.setContentText(body);
}
Intent intent = new Intent(this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, REQUEST_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);
builder.setAutoCancel(true);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification n = builder.build();
n.defaults = Notification.DEFAULT_ALL;
notificationManager.notify(0, n);
}
}
當您的應用程序處於後臺時,可能觸發'onMessageReceived()'***如果您使用'data'- * only *消息負載。請參閱[處理消息文檔](https://firebase.google.com/docs/cloud-messaging/android/receive#handling_messages)瞭解取決於您發送的消息負載的行爲。 –