Gith
Gith

Reputation: 27

Android notification with StartForeground and NotificationManager.Notify

I am starting a foreground service for location monitoring through the below code.

string content = "Tracking started. You can change the tracking settings...";
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
   .SetDefaults((int)NotificationDefaults.All)
   .SetSmallIcon(Resource.Drawable.notification)
   .SetVibrate(new long[] { 100, 200, 300, 400, 500, 400, 300, 200, 400 })
   .SetSound(null)
   .SetChannelId(NOTIFICATION_CHANNEL_ID)
   .SetPriority(NotificationCompat.PriorityDefault)
   .SetAutoCancel(true)
   .SetContentTitle("Smart Office")
   .SetContentText(content)
   .SetOngoing(false);

StartForeground(NOTIFICATION_SERVICE_ID, builder.Build(), Android.Content.PM.ForegroundService.TypeLocation);

This notification does not away with swiping or clicking as it is a foreground service and doesn't have an intent, which is how I want it to be.

Then when the user enters a region, I create a notification with SetAutoCancel(true) and SetContentIntent(pendingIntent) as below.

var pendingIntent = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.UpdateCurrent);

Notification.Builder notificationBuilder = new Notification.Builder(this, NOTIFICATION_CHANNEL_ID)
    .SetSmallIcon(Resource.Drawable.notification)
    .SetContentTitle("Smart Office")
    .SetContentText(message)
    .SetAutoCancel(true)
    .SetContentIntent(pendingIntent)
    .SetOngoing(false);
var notificationManager = (NotificationManager)GetSystemService(NotificationService);
notificationManager.Notify(NOTIFICATION_SERVICE_ID, notificationBuilder.Build());

Now I want this notification to go away with swiping or with clicking on the notification. When clicked it opens the correct intent but the notification doesn't as such go away. What is the reason for this?

Note:If I show this notification before starting the foreground service (ie. before StartForeground(NOTIFICATION_SERVICE_ID, builder.Build(), Android.Content.PM.ForegroundService.TypeLocation); ) then I can swipe the notification away.

Thanks in advance.

Upvotes: 0

Views: 106

Answers (1)

Gith
Gith

Reputation: 27

I had to change the id in the Notify method. I changed

notificationManager.Notify(NOTIFICATION_SERVICE_ID, notificationBuilder.Build());

to

notificationManager.Notify(NOTIFICATION_ALARM_ID, notificationBuilder.Build()); 

and it showed both the notifications.

Upvotes: 0

Related Questions