Starting services
Sometimes, we have to execute a task that must continue to run even if the user switches to another app or activity.
How to do it...
To be able to execute a task, even if the user switches away, we use a Service
instance:
- First, we need an instance of
Service
, and in most cases, we can use anIntentService
instance:[Service] public class XamarinService : IntentService { protected override void OnHandleIntent(Intent intent) { // some long-running task } }
- In order to begin execution, we invoke the
StartService()
method on theContext
type:StartService(new Intent(this, typeof(XamarinService)));
- We can pass data to the service when we start it by adding data to the intent:
var intent = new Intent(this, typeof(XamarinService)); intent.PutExtra("MyKey", ...
Get Xamarin Mobile Development for Android Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.