简体   繁体   中英

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. 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.

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.

[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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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