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", "MyValue"); StartService(intent);
Additionally, in the service, we can retrieve the values from the intent's extras:
string value = null; if (intent.HasExtra("MyKey")) value = intent.GetStringExtra("MyKey");
How it works...
Some...