I am in the process of creating an app that is similar to the built-in SMS app.
What I need:
- a service that is always running in the background
- every 5 min. the service checks the current location of the device and calls a web service
- if certain criteria are met, the service should generate a notification (just like the SMS app)
- when the notification is clicked, the user is taken to the app (just like the SMS app)
- when the app is installed the service should be started
- when the device is rebooted, the service should be started
What I have tried:
- running a regular service which worked just fine until Android kills the service
- using the AlarmManager to make the 5 min. interval call to a service. But I was not able to make this work.
by these three steps, you can wake every 5 minutes most of the Android devices :
1. set your alternative AlarmManager for diffrent APIs :
2. build your own static BroadcastReceiver :
3. add
<receiver>
toAndroidManifest.xml
:This is not possible in any real sense of the term, as you have discovered. It is also bad design.
Use
AlarmManager
.Here is a sample project showing how to use one, along with the use of
WakefulIntentService
so you stay awake while trying to do the whole Web service thing.If you have continued problems with it, open up a new question about the specific things you are encountering with
AlarmManager
that are giving you grief.You can do this by some simple implementation:
You can start service by this :
In manifest:
One of my apps does something very similar. To wake the service after a given period I recommend
postDelayed()
Have a handler field:
and a refresher
Runnable
You can fire your Notifications in the runnable.
On service construction, and after each execution start it like so:
In
onDestroy()
remove the postTo start the service at boot time you need an auto starter. This goes in your manifest
and the
ServiceAutoStarter
looks like this:Stopping the OS from killing the service is tricky. Also your application can have a
RuntimeException
and crash, or your logic can stall.In my case it seemed to help to always refresh the service on screen on with a
BroadcastReceiver
. So if the chain of updates gets stalled it will be resurrected as the user uses their phone.In the service:
In your service
onCreate()
Then unregister your service on
onDestroy()
with