简体   繁体   English

更新 Xamarin.Android 上的通知文本

[英]Update notification text on Xamarin.Android

Currently I have an app which registers a notification as such:目前我有一个注册通知的应用程序:

        public void StartAppService()
        {
            ...

            using (var intent = new Intent(Application.Context, typeof(RunningAppService)))
            {
                Application.Context.StartForegroundService(intent);
            }
        }
        private const int ServiceRunningNotificationId = 10000;

        public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
        {
            CreateNotificationChannel();

            using (var notification = new Notification.Builder(this, "10111")
                .SetContentTitle("Artemis HZ")
                .SetContentText("90 HZ")
                .SetSmallIcon(Resource.Drawable.icon)
                .SetOngoing(true)
                .Build())
            {
                StartForeground(ServiceRunningNotificationId, notification);
            }

            ...

            return StartCommandResult.Sticky;
        }
        private void CreateNotificationChannel()
        {
            const string channelName = "TopAppServiceChannel";
            const string channelDescription = "TopAppServiceChannel";
            using (var channel = new NotificationChannel("10111", channelName, NotificationImportance.Default)
            {
                Description = channelDescription
            })
            {
                using (var notificationManager = (NotificationManager)GetSystemService(NotificationService))
                {
                    notificationManager?.CreateNotificationChannel(channel);
                }
            }
        }

And I want to change it's SetContentText programmatically.我想以编程方式更改它的 SetContentText 。 I tried doing it like this:我试着这样做:

                using (var notificationBuilder = new Notification.Builder(this, "10111")
                    .SetContentText($"{(int)hz} HZ"))
                {
                    using (var notificationManager = (NotificationManager)GetSystemService(NotificationService))
                    {
                        notificationManager?.Notify(10111, notificationBuilder.Build());
                    }
                }

and nothing happens.什么也没有发生。 It only works in the first seconds of the app launching but after that it just stays put to whatever it was and won't change again.它仅在应用程序启动的最初几秒钟内有效,但在那之后它只是保持不变并且不会再次更改。

The code you provided seems okay.您提供的代码似乎还可以。 When you send the notifications again, you use the same notiication id "10111" and the old notification would be covered.当您再次发送通知时,您使用相同的通知 ID“10111”,旧通知将被覆盖。

You could check the code below about how to send the notification with thedifferent channels.您可以查看下面的代码,了解如何使用不同的渠道发送通知。 If you want to show more notifications, you could change the notification id.如果要显示更多通知,可以更改通知 ID。

[Activity(Label = "@string/app_name", Theme = "@style/AppTheme", MainLauncher = true)]
public class MainActivity : AppCompatActivity
{
    // Unique ID for our notification: 
    internal static readonly int NOTIFICATION_ID_1 = 1001;
    static readonly int NOTIFICATION_ID_2 = 1002;
    static readonly int NOTIFICATION_ID_3 = 1003;
    static readonly int NOTIFICATION_ID_4 = 1004;

    static readonly string CHANNEL_ID1 = "channel_1";
    static readonly string CHANNEL_ID2 = "channel_2";
    static readonly string PRIMARY_CHANNEL_ID = "channel_3";
    internal static readonly string COUNT_KEY = "count";

    // Number of times the button is tapped (starts with first tap):
    int count = 1;

    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        Xamarin.Essentials.Platform.Init(this, savedInstanceState);
        // Set our view from the "main" layout resource
        SetContentView(Resource.Layout.Main_layout);

        CreateNotificationChannel1();
        

        // Normall CHANNEL Ntification channel
        var btnChannel = FindViewById<Button>(Resource.Id.btnChannel);
        btnChannel.Click += delegate
        {
            // Pass the current button press count value to the next activity:
            var valuesForActivity = new Bundle();
            valuesForActivity.PutInt(COUNT_KEY, count);

            // When the user clicks the notification, SecondActivity will start up. Set up an intent so that tapping the notifications returns to this app:
            var resultIntent = new Intent(this, typeof(SecondActivity));

            // Pass some values to SecondActivity:
            resultIntent.PutExtras(valuesForActivity);

            // Construct a back stack for cross-task navigation:
            var stackBuilder = Android.Support.V4.App.TaskStackBuilder.Create(this);
            stackBuilder.AddParentStack(Class.FromType(typeof(SecondActivity)));
            stackBuilder.AddNextIntent(resultIntent);

            // Create the PendingIntent with the back stack:            
            var resultPendingIntent = stackBuilder.GetPendingIntent(0, (int)PendingIntentFlags.UpdateCurrent);//FLAG

            // Build the notification:
            var builder = new NotificationCompat.Builder(this, CHANNEL_ID1)
                          .SetAutoCancel(true) // Dismiss the notification from the notification area when the user clicks on it
                          .SetContentIntent(resultPendingIntent) // Start up this activity when the user clicks the intent.
                          .SetContentTitle("Button Notification Channel_1") // Set the title
                          .SetNumber(count) // Display the count in the Content Info
                          .SetSmallIcon(Resource.Drawable.z) // This is the icon to display
                          .SetLargeIcon(BitmapFactory.DecodeResource(Resources, Resource.Drawable.Icon))
                          .SetContentText($"The button has been clicked {count} times."); // the message to display.
            builder.SetVisibility(NotificationCompat.VisibilityPublic);


            // Finally, publish the notification:
            var notificationManager = NotificationManagerCompat.From(this);
            notificationManager.Notify(NOTIFICATION_ID_1, builder.Build());

            // Increment the button press count:
            count++;
        };

        
      

      
    }

    void CreateNotificationChannel1()
    {
        if (Build.VERSION.SdkInt < BuildVersionCodes.O)
        {
            // Notification channels are new in API 26 (and not a part of the
            // support library). There is no need to create a notification 
            // channel on older versions of Android.
            return;
        }
        var alarmAttributes = new AudioAttributes.Builder()
               .SetContentType(AudioContentType.Sonification)
               .SetUsage(AudioUsageKind.Notification).Build();

        var path = Android.Net.Uri.Parse("android.resource://com.companyname.NotificationChannelsDemo/" + Resource.Raw.Hello);//Android.Net.Uri.Parse("ContentResolver.SchemeAndroidResource:" + "//com.companyname.NotificationChannelsDemo/" + Resource.Raw.Hello)
        var name = Resources.GetString(Resource.String.channel_name);
        var description = GetString(Resource.String.channel_description);
        var channel = new NotificationChannel(CHANNEL_ID1, name, NotificationImportance.Max)
        {
            Description = description
        };
        //channel.SetSound(path, alarmAttributes);
        var notificationManager = (NotificationManager)GetSystemService(NotificationService);
        notificationManager.CreateNotificationChannel(channel);
    }
 

    public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
    {
        Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);

        base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}

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

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