首页 > 解决方案 > Android:通知不会显示

问题描述

我正在我的应用程序中开发一个简单的服务,该服务还发送通知以向用户显示该服务正在运行。这确实有效,但从一天到另一天都停止了。我知道代码被正确调用了。我在这些行中设置了一个测试吐司,每半秒调用一次,所以它应该可以工作,但通知栏中没有显示通知。请看一看:

void DispatchNotificationThatServiceIsRunning()
        {
            _notificationIsLive = true;

            RemoteViews contentView = new RemoteViews(PackageName, Resource.Layout.Notification);
            contentView.SetTextViewText(Resource.Id.txt_crrentSong_notification, Activity_Player.txt_CurrentSong.Text);
            contentView.SetTextViewText(Resource.Id.txt_crrentSong__artist_notification, Activity_Player.txt_CurrentArtist.Text);

            notificationBuilder = new Notification.Builder(this);

            Task.Delay(_countDownFirstRound).ContinueWith(t =>
            {
                notificationBuilder
                .SetSmallIcon(Resource.Drawable.btn_icon_header)
                .SetCustomContentView(contentView);

                var notificationManager = (NotificationManager)GetSystemService(NotificationService);
                notificationManager.Notify(50, notificationBuilder.Build());

                DispatchNotificationThatServiceIsRunning();//This is for repeate every 1s.

                _countDownFirstRound = 50;

                // Click on notification, and return to app. Only works, because _2TimerRunning is set as : "LaunchMode = LaunchMode.SingleInstance"
                Intent notificationIntent = new Intent(this, typeof(Activity_Player));
                notificationIntent.SetAction(Intent.ActionMain);
                notificationIntent.AddCategory(Intent.CategoryLauncher);
                PendingIntent contentIntent = PendingIntent.GetActivity(this, 1, notificationIntent, PendingIntentFlags.UpdateCurrent);
                notificationBuilder.SetContentIntent(contentIntent);

            }, 

            TaskScheduler.FromCurrentSynchronizationContext());
        }

    }

标签: android

解决方案


从 Android 8.0(API 级别 26)开始,所有通知都必须分配给一个频道。请参阅此链接..创建和管理通知渠道

在 notificationManager.Notify(50, notificationBuilder.Build()); 之前添加此代码

String channelId = "Default";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(channelId, "Default channel", NotificationManager.IMPORTANCE_DEFAULT);
            notificationManager.createNotificationChannel(channel);
        }

推荐阅读