We might have a long-running task that we need to execute when the device starts. This may be needed to set up some service or configuration for other services.
When we want to perform a task when the device starts up, we can start a service when we receive the ActionBootComplete
intent action:
[assembly: UsesPermission( Manifest.Permission.ReceiveBootCompleted)]
Service
instance that will perform the actual task:[Service] public class XamarinService : IntentService { protected override void OnHandleIntent(Intent intent) { // some startup task } }
BroadcastReceiver
instance:[BroadcastReceiver] [IntentFilter(new []{ Intent.ActionBootCompleted })] public class ServiceStarter : BroadcastReceiver { public override void OnReceive( Context context, Intent intent) { var serviceIntent = new Intent( context, typeof(XamarinService)); context.StartService(serviceIntent); } }
var intent = new Intent(this, typeof(XamarinService)); StartService(intent);
If we want to perform any task as soon as the device starts up, for example to start a service or to execute a configuration or security task, we need to register a broadcast receiver with the Android OS.
Before we can register for the boot notification, we need to request permission to do so. This is done by requesting the ReceiveBootCompleted
permission. Another important aspect to realize is that the app has to be launched manually by the user at least once before the receiver is allowed to receive the intent. Also, if the user force stops the app from the device settings, they will have to relaunch the app before the receiver is registered.
In order to listen for the ActionBootCompleted
intent, we need to create a BroadcastReceiver
instance that filters the ActionBootCompleted
action. As soon as the device has finished booting, it will broadcast the intent and we will be able to perform a task.
As a BroadcastReceiver
instance usually executes the OnReceive()
method on the UI thread, we need to execute the task on a new thread. However, we cannot use asynchronous tasks in a broadcast receiver, because as soon as the OnReceive()
method is returned, the receiver is terminated, and if there are any threads, they will be leaked. Thus, we should use a service with a broadcast receiver.
As the intent is broadcasted when the device is booted, we need to ensure that even if the user does not reboot the device, we still perform the tasks when the user launches the app. For example, if we want to start a service when the device is booted, we have to ensure that if the app is launched without rebooting, we start the service manually.