我刚刚迁移到androidx来实现Firebase消息传递。我已将所有内容更改为 androidx,并将我的应用程序连接到 Firebase。起初,当我从Firebase控制台发送通知时,它会崩溃。为了避免崩溃,我将FirebaseApp.initializeApp(this);
放在我的 MainActivity 中。
但是我仍然没有在通知列表中看到任何通知。
在我的Manifest
里,我把
<service android:name=".MyFirebaseMessagingService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
对于MyFirebaseMessagingService
public class MyFirebaseMessagingService extends FirebaseMessagingService {
public static final String TAG = "FirebaseSerive";
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
String title = remoteMessage.getData().get("title");
String body = remoteMessage.getData().get("body");
Notification notification = new Notification.Builder(this)
.setContentTitle(title)
.setContentText(body)
.setSmallIcon(R.drawable.ss_icon)
.build();
NotificationManagerCompat manager = NotificationManagerCompat.from(getApplicationContext());
manager.notify(/*notification id*/0, notification);
}
}
更新我的代码后,我的模拟器显示Failed to post notification on channel “null”
提前感谢您的帮助。希望你能帮助我。
您可以尝试使用OREO中引入的这个频道。可能是导致问题的原因。
public class MyFirebaseMessagingService extends FirebaseMessagingService {
public static final String TAG = "FirebaseSerive";
public static final String NOTIFICATION_CHANNEL_ID = "IMP_NOTIFICATIONS";
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
String title = remoteMessage.getNotification().getTitle();
String body = remoteMessage.getNotification().getBody();
Notification.Builder notification = new Notification.Builder(this)
.setContentTitle(title)
.setContentText(body)
.setSmallIcon(R.drawable.ss_icon);
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "NOTIFICATION_CHANNEL_NAME", importance);
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.enableVibration(true);
notificationChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
assert mNotificationManager != null;
notification.setChannelId(NOTIFICATION_CHANNEL_ID);
mNotificationManager.createNotificationChannel(notificationChannel);
}
mNotificationManager.notify(/*notification id*/0, notification.build());
}
}
编辑:可能是您正在获得通知有效负载而不是数据,您可以使用以下代码进行检查。
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
}
例如,在此处阅读更多内容。
文档