I wrote an app which monitors my signal strength via a PhoneStateListener. I want this app to start up at boot time and run forever.
The way I managed this is as follows, but I'd like to know if anyone can recommend a better way of doing this.
I have registered a BroadcastReceiver which runs upon BOOT_COMPLETED.
Within this BOOT_COMPLETED BroadcastReceiver, I start a Service.
The Service starts up my PhoneStateListener.
Within my BOOT_COMPLETED BroadcastReceiver, I also start a periodic alarm via AlarmManager.setInexactRepeating.
Whenever this alarm fires off, it checks if my Service is running. If it's not running, it restarts my Service, which in turn restarts my PhoneStateListener.
This all seems to be working for me, but I'm wondering if it's the best and most efficient way to ensure that a PhoneStateListener is running all the time (or at least most of the time).
Is there perhaps a better way to manage this?
Thanks in advance.
You can make your service a foreground service, in this case your service is really unlikely to be killed (only if the currently opened app needs more memory).
In this case your app must show an ongoing notification to the user while the service is in foreground.
To do so, you must call the startForeground()
method of your service, providing a notification to it:
startForeground(ONGOING_NOTIFICATION_ID, notification);
Check for more info: http://developer.android.com/guide/components/services.html#Foreground