繁体   English   中英

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

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

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

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。 我想找到一种方法,如何为 sdk 版本 < 25 重写 NotificationCompat.Builder。如果我尝试用旧样式编写它,Android Studio 说该方法已被贬低。

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

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

您可以将new NotificationCompat.Builder(this, CHANNEL_ID)用于任何 SDK 级别,但您需要为 SDK >= 26 的设备创建NotificationChannel ,如果 ZF20E36FAZ6 <2063FAB96D6 2063FAB96D,则无需创建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());

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM