Android studio:当应用程序在前台时无法在 sdk < 26 上接收推送消息

Android studio: cant recieve push messages on sdk < 26 when app is on foreground

我想让我的应用在前台查看推送通知。它在我的模拟器上工作正常(在前台和后台接收),但是当推送到我的前台 phone 时,应用程序崩溃了。 这是我的代码:

if (android.os.Build.VERSION.SDK_INT >= 26) {
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
            channel.setDescription(CHANNEL_DESC);

            NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
                    .setSmallIcon(android.R.drawable.stat_notify_more)
                    .setContentTitle(remoteMessage.getNotification().getTitle())
                    .setContentText(remoteMessage.getNotification().getBody());

            NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            manager.createNotificationChannel(channel);
            manager.notify(1, builder.build());
        }

我的 phone 有 android 7.1 版本,所以应用程序与 NotificationChannels 一致。据我了解,NotificationChannels 不适用于 android 的旧版本。我想找到一种方法,如何为小于 25 的 sdk 版本重写 NotificationCompat.Builder。如果我尝试以旧样式编写它,Android Studio 说 methid 已被删除。

NotificationCompat.Builder builder = new NotificationCompat.Builder(this)

使 NotificationCompat.Builder 在旧的 sdk 版本上工作的正确方法是什么?或者如何让我的应用程序在 android 不支持 NotificationChannels 的版本的前台接收消息?

您可以对任何 SDK 级别使用 new NotificationCompat.Builder(this, CHANNEL_ID),但您需要为 SDK >= 26 的设备创建 NotificationChannel,如果 SDK < 26.


试试这个代码

private void createNotification() {

    NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    // only create notification channel if SDK >= 26
    if (android.os.Build.VERSION.SDK_INT >= 26) {
        NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
        channel.setDescription(CHANNEL_DESC);
        manager.createNotificationChannel(channel);
    }

    NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
            .setSmallIcon(android.R.drawable.stat_notify_more)
            .setContentTitle(remoteMessage.getNotification().getTitle())
            .setContentText(remoteMessage.getNotification().getBody());


    manager.notify(1, builder.build());

}