Xamarin前台服务通知不会更改其文本

时间:2018-08-08 13:42:53

标签: c# xamarin service notifications foreground

我使用的前台服务正常启动,显示第一个通知,但是尽管NotificationManager.Notify()方法可以正常运行且没有错误,但是通知文本不会更改。我尝试调试,代码每1秒就可以完美地运行一个计时器,但是更新没有发生。 -它必须更新为Datetime.Now

在我的服务舱内:

 private void ActivityTimer_Elapsed(object sender, ElapsedEventArgs e)
    {
        updateNotification();
    }

    private NotificationChannel createNotificationChannel()
    {
        var channelId = Constants.NOTIFICATION_CHANNELID;
        var channelName = "My Notification Service";
        var Channel = new NotificationChannel(channelId, channelName, Android.App.NotificationImportance.None);
        Channel.LightColor = Android.Resource.Color.HoloBlueBright;
        Channel.LockscreenVisibility = NotificationVisibility.Public;
        return Channel;
    }

    private void createForegroundService()
    {
        var mNotificationManager = GetSystemService(Context.NotificationService) as NotificationManager;
        if (Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.O)
        {
            mNotificationManager.CreateNotificationChannel(createNotificationChannel());
        }
        var notificationBuilder = new NotificationCompat.Builder(this, Constants.NOTIFICATION_CHANNELID);
        var notification = getNotification();
        StartForeground(Constants.NOTIFICATION_ID, notification);

    }
    private void updateNotification()
    {
        var mNotificationManager = GetSystemService(Context.NotificationService) as NotificationManager;
        if (Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.O)
        {
            mNotificationManager.CreateNotificationChannel(createNotificationChannel());
        }

        var notification = getNotification();

        mNotificationManager.Notify(Constants.NOTIFICATION_ID, notification);
    }

    private Notification getNotification()
    {
        PendingIntent pIntent = PendingIntent.GetActivity(this,0,new Intent(this,typeof(MainActivity)),0);
        return new Notification.Builder(this,Constants.NOTIFICATION_CHANNELID)
            .SetColor(Android.Resource.Color.DarkerGray)
            .SetContentTitle("My service name")
            .SetOngoing(true)
            .SetContentText(DateTime.Now.ToString("T"))
            .SetSmallIcon(Resource.Drawable.notification_icon_background)
            .SetContentIntent(pIntent).Build();
    }

1 个答案:

答案 0 :(得分:0)

已解决。问题出在这里: var Channel = new NotificationChannel(channelId, channelName, Android.App.NotificationImportance.**None**); <-保留为NotificationImportance.Default