为什么在Android 9上没有通知显示

3

在 Android 9.0 上没有显示通知,但在8.0及以下版本上运行良好。我遇到了旧代码的问题,经过阅读发现需要在新的 Android 版本上传递 Channel,我从网上获取了这段代码,但仍无法在 Android 9.0 上工作。我不知道为什么。

我阅读了互联网上的所有内容,但通知仍未显示。

    private void showSmallNotification( int icon, String title, String message, String timeStamp, PendingIntent resultPendingIntent){
        String CHANNEL_ID = Constants.ChannelID;
        String CHANNEL_NAME = "Notification";

        NotificationManager notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);;
        NotificationCompat.Builder notification;
        NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();

        inboxStyle.addLine(message);

        if (Build.VERSION.SDK_INT >= 26) {
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
            channel.enableVibration(true);
            channel.setLightColor(Color.BLUE);
            channel.enableLights(true);
            channel.setSound(Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + getApplicationContext().getPackageName() + "/" + R.raw.notification),
                    new AudioAttributes.Builder()
                            .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                            .setUsage(AudioAttributes.USAGE_NOTIFICATION)
                            .build());
            channel.canShowBadge();
            notificationManager.createNotificationChannel(channel);
            notification = new NotificationCompat.Builder(getApplicationContext(), CHANNEL_ID);
        } else {
            notification = new NotificationCompat.Builder(getApplicationContext(),CHANNEL_ID);
        }
        notification
                .setVibrate(new long[]{0, 100})
                .setPriority(Notification.PRIORITY_MAX)
                .setLights(Color.BLUE, 3000, 3000)
                .setAutoCancel(true)
                .setContentTitle(title)
                .setContentIntent(resultPendingIntent)
                .setWhen(getTimeMilliSec(timeStamp))
                .setSmallIcon(R.mipmap.ic_launcher)
                .setStyle(inboxStyle)
                .setLargeIcon(BitmapFactory.decodeResource(this.getResources(), icon))
                .setContentText(message)
                .build();

        notificationManager.notify(CHANNEL_ID, 1, notification.build());
    }
3个回答

2
我认为问题在于您没有在notificationBuilder上调用setChannelId()。(我冒昧地将notification重命名为notificationBuilder,因为它就是这样。)
我删除了一行代码中的多余分号。
此外,请注意canShowBadge()是一个返回值的类方法,但不设置任何通知设置。我用setShowBadge(true)替换了它。
请阅读我在代码片段中留下的注释以获取更多信息。
Original Answer翻译成"最初的回答"
private void showSmallNotification( int icon, String title, String message, String timeStamp, PendingIntent resultPendingIntent){
        String CHANNEL_ID = Constants.ChannelID;
        String CHANNEL_NAME = "Notification";

        // I removed one of the semi-colons in the next line of code
        NotificationManager notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
        NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();

        inboxStyle.addLine(message);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            // I would suggest that you use IMPORTANCE_DEFAULT instead of IMPORTANCE_HIGH
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
            channel.enableVibration(true);
            channel.setLightColor(Color.BLUE);
            channel.enableLights(true);
            channel.setSound(Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + getApplicationContext().getPackageName() + "/" + R.raw.notification),
                    new AudioAttributes.Builder()
                            .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                            .setUsage(AudioAttributes.USAGE_NOTIFICATION)
                            .build());
            //channel.canShowBadge();
            // Did you mean to set the property to enable Show Badge?
            channel.setShowBadge(true);
            notificationManager.createNotificationChannel(channel);
        }

        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(getApplicationContext(), CHANNEL_ID)
            .setVibrate(new long[]{0, 100})
            .setPriority(Notification.PRIORITY_MAX)
            .setLights(Color.BLUE, 3000, 3000)
            .setAutoCancel(true)
            .setContentTitle(title)
            .setContentIntent(resultPendingIntent)
            .setWhen(getTimeMilliSec(timeStamp))
            .setSmallIcon(R.mipmap.ic_launcher)
            .setStyle(inboxStyle)
            .setLargeIcon(BitmapFactory.decodeResource(this.getResources(), icon))
            .setContentText(message);
        // Removed .build() since you use it below...no need to build it twice

        // Don't forget to set the ChannelID!!
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
            notificationBuilder.setChannelId(ID_SPECIAL_OFFER_NOTIFICATION);
        }

        notificationManager.notify(CHANNEL_ID, 1, notificationBuilder.build());
    }

抱歉回复晚了,但仍未显示通知。 - Web.11
你在正确的位置添加了“setChannelId”到你的代码中吗? - Barns
@Web.11,我也遇到了同样的问题。你是怎么解决的? - Keselme
@Barns,我尝试了你建议的解决方案,还有其他什么我可以尝试的吗? - Keselme
@Keselme 抱歉,我没有 Android 9.0 设备进行测试。但是在其他设备上,以上代码没有出现任何问题。祝你好运!# - Barns

0

好的,这段代码现在对我来说可以工作了,并且已经测试过到 Android 12。 首先我创建了一个通道。

// Create Channel For Notifications (if does not exist)
private void createNotificationChannel() {
    // Create the NotificationChannel, but only on API 26+ because
    // the NotificationChannel class is new and not in the support library
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationManager mNotificationManager = getSystemService(NotificationManager.class);
        NotificationChannel existingChannel = mNotificationManager.getNotificationChannel(Constants.notification_channel_ID);
        // If channel does not exist then create.
        if (existingChannel == null) {
            CharSequence name = getResources().getString(R.string.app_name);
            String description = getResources().getString(R.string.notification_description);
            int importance = NotificationManager.IMPORTANCE_DEFAULT;
            NotificationChannel notificationChannel = new NotificationChannel( Constants.notification_channel_ID , name , importance) ;
            notificationChannel.setDescription(description);
            notificationChannel.enableLights(true) ;
            notificationChannel.setLightColor(Color.BLUE) ;
            NotificationManager notificationManager = getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(notificationChannel);
        }
    }
}

也许不需要检查通道是否存在,但我会检查。 然后当我需要显示通知时,我调用这个方法:

private void notification(){
     Intent intent = new Intent(this, MainActivity.class);
     intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
     intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
     PendingIntent pendingIntent = Build.VERSION.SDK_INT >= Build.VERSION_CODES.M ? PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE) : PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    
     NotificationCompat.Builder builder = new NotificationCompat.Builder(this, Constants.notification_channel_ID)
                                .setChannelId(Constants.notification_channel_ID)
                                .setSmallIcon(R.mipmap.ic_launcher)
                                .setContentTitle(this.getResources().getString(R.string.app_name))
                                .setContentText(this.getResources().getString(R.string.description))
                                .setContentIntent(pendingIntent)
                                .setAutoCancel(true);
      NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
      notificationManager.notify(Constants.NOTIFICATION_ID, builder.build());
}

0

是的,这个问题已经有答案了,但还需要帮助那些需要的人。

 @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        int returnFlag = 0;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            createNotificationChannel();
            Notification.Builder builder = new Notification.Builder(this, ANDROID_CHANNEL_ID)
                    .setContentTitle(getString(R.string.app_name))
                    .setContentText("Mytrux Running")
                    .setAutoCancel(true);
            Notification notification = builder.build();
            startForeground(NOTIFICATION_ID, notification);
            returnFlag = START_NOT_STICKY;
        } else {
            NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                    .setContentTitle(getString(R.string.app_name))
                    .setContentText("Mytrux is Running...")
                    .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                    .setAutoCancel(true);
            Notification notification = builder.build();
            startForeground(NOTIFICATION_ID, notification);
            returnFlag = START_STICKY;
        }
        mHandlerTask.run();
        return returnFlag;
    }

并且也添加这个方法

private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel serviceChannel = new NotificationChannel(
                    ANDROID_CHANNEL_ID,
                    "Foreground Service Channel",
                    NotificationManager.IMPORTANCE_DEFAULT
            );

            NotificationManager manager = getSystemService(NotificationManager.class);
            manager.createNotificationChannel(serviceChannel);
        }
    }

不要忘记在清单文件中添加服务。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接