首页 > 解决方案 > 如何在 API 26 中添加音乐播放器通知

问题描述

我已经设法显示通知,但问题是它没有按预期工作。问题是 - 1. 我不知道如何将通知保持在顶部 2. 当我滑动通知时,它会显示贪睡图标,但不会在任何其他音乐应用程序中显示。

这是我的代码

`if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    RemoteViews expandedView = new RemoteViews(getContext().getPackageName(), R.layout.custom_push);
                    CharSequence name = "Music Player";
                    String description = "Play music in background";
                    int importance = NotificationManager.IMPORTANCE_LOW;
                    NotificationChannel channel = new NotificationChannel("Music Player", name, importance);
                    channel.setDescription(description);
                    channel.setShowBadge(false);
                    // Register the channel with the system; you can't change the importance
                    // or other notification behaviors after this
                    NotificationCompat.Builder nc = new NotificationCompat.Builder(getContext(),"Music Player");
                    Intent notifyIntent = new Intent(getContext(), now_playing.class);

                    notifyIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    PendingIntent pendingIntent = PendingIntent.getActivity(getContext(),0,notifyIntent,PendingIntent.FLAG_UPDATE_CURRENT);
                    nc.setContentIntent(pendingIntent);
                    nc.setCustomBigContentView(expandedView);
                    nc.setSmallIcon(R.drawable.notification_icon);
                    nc.setAutoCancel(false);
                    nc.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
                    nc.setOngoing(true);
                    NotificationManager notificationManager = getActivity().getSystemService(NotificationManager.class);
                    notificationManager.createNotificationChannel(channel);
                    notificationManager.notify(1, nc.build());
                }`

另外我注意到其他音乐播放器在设置中没有任何通知渠道。如果有人告诉我如何正确实施通知,那就太好了。 谢谢

标签: javaandroidandroid-studionotificationsandroid-8.0-oreo

解决方案


创建通知通道时将通知重要性设置为高 NotificationManger.IMPORTANCE_HIGH

  NotificationChannel channel = new NotificationChannel(channelId, ChannelName, NotificationManager.IMPORTANCE_HIGH);

推荐阅读