Xamarin Android Services

  • Details of basic Xamarin Android Services

  • It is important to note that the service will run on the main thread, so any long-running work must be kept on a separate thread

  • In order to conserve system resources, a started service implementation calls StopSelf after any long-running work is done. This is important because the service will run independently of the component that called StartService. Therefore, the service will keep running even after the starting component, such as an Activity, is destroyed.

  • A service runs on the main thread, so any long-running task would block the main thread, making the application unresponsive. Therefore, such code should be implemented on a separate thread in the service.

  • eg:

var t = new Thread (() => {
        // long running code ...            
});
t.Start();
  • Any UI updates that are made directly from code in a service that is running on a separate thread can be performed in the Post method of a handler as follows:
var myHandler = new Handler ();
...
myHandler.Post(() => {
        Toast.MakeText (this, "Message from demo service", ToastLength.Long).Show();
});