【问题标题】:Android studio: cant recieve push messages on sdk < 26 when app is on foregroundAndroid Studio:当应用程序在前台时,无法在 sdk < 26 上接收推送消息
【发布时间】:2019-11-20 15:15:55
【问题描述】:

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

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());
        }

我的手机是 android 7.1 版本,所以应用程序会在 NotificationChannels 上线。据我了解,NotificationChannels 不适用于旧版本的 android。我想找到一种方法,如何为

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

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

【问题讨论】:

    标签: java android firebase push-notification android-notifications


    【解决方案1】:

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


    试试这个代码

    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());
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-28
      • 1970-01-01
      • 2013-09-07
      • 2015-04-04
      • 2020-06-21
      • 1970-01-01
      相关资源
      最近更新 更多