FCM 升级后 Android API 级别 26+ 上未显示通知

Notification not showing on Android API level 26+ after FCM upgrade

下面的代码似乎没有在我的模拟器上显示通知。我从已弃用的 Firebase 代码升级到带有频道的新内容。有什么我应该调查的吗?

<application android:icon="@drawable/icon" android:allowBackup="false" android:label="@string/application_label" android:theme="@style/Theme">
        <meta-data android:name="com.google.firebase.messaging.default_notification_icon" android:resource="@drawable/icon" />
        <meta-data android:name="com.google.firebase.messaging.default_notification_color" android:resource="@color/accentColor" />
        <meta-data android:name="com.google.firebase.messaging.default_notification_channel_id" android:value="@string/default_notification_channel_id" />
        ......
        <service
            android:name="com.exposure.services.ExposureFirebaseMessagingService">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT"/>
            </intent-filter>
        </service>
    </application>

来自 Android Oreo,您必须使用频道来创建通知。

Starting in Android 8.0 (API level 26), all notifications must be assigned to a channel. For each channel, you can set the visual and auditory behavior that is applied to all notifications in that channel. Then, users can change these settings and decide which notification channels from your app should be intrusive or visible at all.


Caution: If you target Android 8.0 (API level 26) and post a notification without specifying a notification channel, the notification does not appear and the system logs an error.

阅读更多文档:https://developer.android.com/training/notify-user/channels


显然,您已经为通知使用了通知渠道,但尚未创建与该 ID 关联的通知渠道。因此您需要在创建通知之前创建一个通知通道。

创建通知渠道的示例(可能在您的 FCM 服务 class 中)如下所示:

@Override
public void onCreate() {
    super.onCreate();
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
        // Make sure you use the same channel id ("default" in this case)
        // while creating notifications.
        NotificationChannel channel = new NotificationChannel("default", "Default Channel",
                NotificationManager.IMPORTANCE_HIGH);
        channel.setDescription("Default Notification Channel");
        NotificationManager notificationManager = (NotificationManager)
                getSystemService(NOTIFICATION_SERVICE);
        if (notificationManager != null) {
            notificationManager.createNotificationChannel(channel);
        }
    }
}

根据Google开发者方https://developer.android.com/training/notify-user/channels

创建通知前请使用通知渠道