Skip to content Skip to sidebar Skip to footer

Xamarin.android Background Task Disposed After Application Closed

Task: Create a background task to run when application is stopped/paused that periodically (3-7 seconds) performs HTTP requests and stores response information in mysqlite and disp

Solution 1:

I think you are using Foreground Services.

you should dispatch the service notification(foreground notification) by StartForeground method.

So try to change

privatevoidDispatchNotificationThatServiceIsRunning()
{
  NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
       .SetDefaults((int)NotificationDefaults.All)
       .SetSmallIcon(Resource.Drawable.icon)
       .SetVibrate(newlong[] { 100, 200, 300, 400, 500, 400, 300, 200, 400 })
       .SetSound(null)
       .SetChannelId(NOTIFICATION_CHANNEL_ID)
       .SetPriority(NotificationCompat.PriorityDefault)
       .SetAutoCancel(false)
       .SetContentTitle("Mobile")
       .SetContentText("My service started")
       .SetOngoing(true);

  NotificationManagerCompat notificationManager = NotificationManagerCompat.From(this);

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

}

to

privatevoidDispatchNotificationThatServiceIsRunning()
{
  NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
       .SetDefaults((int)NotificationDefaults.All)
       .SetSmallIcon(Resource.Drawable.icon)
       .SetVibrate(newlong[] { 100, 200, 300, 400, 500, 400, 300, 200, 400 })
       .SetSound(null)
       .SetChannelId(NOTIFICATION_CHANNEL_ID)
       .SetPriority(NotificationCompat.PriorityDefault)
       .SetAutoCancel(false)
       .SetContentTitle("Mobile")
       .SetContentText("My service started")
       .SetOngoing(true);

  NotificationManagerCompat notificationManager = NotificationManagerCompat.From(this);

  //dispatch foreground notification
  StartForeground(NOTIFICATION_SERVICE_ID, builder.Build());

}

Post a Comment for "Xamarin.android Background Task Disposed After Application Closed"