1

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.

HippoMan
  • 2,119
  • 2
  • 25
  • 48

1 Answers1

1

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

hunyadym
  • 2,213
  • 25
  • 39
  • Thank you very much. I neglected to mention in my original post that I prefer not to make this a foreground service. The purpose of the app is to help save power, and putting the service into the foreground defeats that purpose. So anyway, I guess that the method I outlined is probably the best I can do without putting the service into the foreground. – HippoMan Oct 11 '15 at 10:05
  • I'm not an expert on power usage questions, but since most of the power usage is because the device is awake, and I think putting your service to foreground doesn't make the device more awake than having a normal service which is never killed as you intended (instead, maybe a little less, because you don't have to wake up the device to check if your service is running). Foreground services can be dangerous for power usage if they consume a lot of memory, and the system has to shut down other apps because of it, but that's the same if you force start your service regularly. – hunyadym Oct 11 '15 at 14:05