How do asynchronous Tasks in Xamarin.Forms work with iOS/Android background modes

Viewed 794

I've read the Microsoft Docs about backgrounding on mobile and have seen the various lifecycle states the app can be in. But I'm still a bit confused about the idea of a background Task in C# and the idea of backgrounding in iOS/Android.

Question:
Let's say I start a new background C# Task, in a ViewModel or Model class (exact pattern irrelevant). It receives data via a WebSocket as well as makes HTTP requests, and keeps running indefinitely. Does this task continue to run when the app is moved to the background by the user? If not, why, and what would I need to do to ensure it keeps running?

1 Answers

In the Android part, you can use dependence service to open a foregroud service.

https://docs.microsoft.com/en-us/xamarin/android/app-fundamentals/services/foreground-services

You can run your Https requests in the foreground service, it will push a notification and keep the service alive when the application is moved to the background by user.

Here is my answer about use foreground service, you can refer to it as well. How to running method webservice in background from android xamarin form

In the IOS part, I suggest you achieve it with Backgrounding with Tasks.

https://docs.microsoft.com/en-us/xamarin/ios/app-fundamentals/backgrounding/ios-backgrounding-techniques/ios-backgrounding-with-tasks

You can put your background HTTP request to BeginBackgroundTask method like following format code.

nint taskID = UIApplication.SharedApplication.BeginBackgroundTask( () => {

// your  background HTTP request
});
Related