I have tried various ways to achieve this, but my service eventually gets killed.
I want to use AlarmManager to trigger a class every one hour. Even if the device is sleeping, it should sent a flashing LED alert, vibration or sound. In any case, it should run forever.
I have noticed that Whatsapp is always running, even though I kill all the running apps and clear the memory, put the device to sleep, and still Whatsapp receive messages and alerts me. How are they doing it? I want to do the same with my app.
You can use a function startForeground(int, Notification) see here and here
Follow these easy steps to keep servce alive forever in android device. 1. Call a service by using alarm manager. 2. return START_STICKY in onStart method. 3. In on destroy call the alarm manager and restart service by using startService method. 4.(Optional)Repeat the point number 3 in onTaskRemoved method.
Request partial WakeLock.
onStartCommand retrun START_STICKY :
Since I posted this question, I have implemented two different approaches to this solution into multiple apps.
This extract is from an app where I use push notifications, which need instant wake up calls for the device. Here what I do is
Manifest:
WakeLocker class:
Activity class example:
Best when you want to give Android control over wake up, and can live with periodically waking up your code. Simply use an AlarmManager to invoke a Service class at regular intervals. Here is some code from my LifeLog24 app:
MainActivity
Alarm Class
and LifeLogService.class is where I do my stuff. Alarm wakes up every hour in this case and triggers the BroadcastReceiver which in return runs the service. There is more to it, to make sure service is not run twice and so on, but you get the point how it is done. And AlarmManager is actually the best way to do it since you don't worry about battery usage, etc. and Android takes care of waking up your Service at regular intervals.
It is very simple.
steps:
1.create a Service class.
2.create a BroadcastReceiver class
3.call BroadReceiver in onDestroy method of service
4.In onReceive method of BroadReceiver class start service once again.
Here's the code
Manifest file:`
`
Service class
BroadcastReceiver class