In the https://github.com/commonsguy/cwac-wakeful demo, the OnAlarmReceiver (a BroadcastReceiver) onReceive() method is called in response to an Alarm. The onReceive() method starts the Service. There are two Intents used, one received by the BroadcastReceiver and one by the Service. This seems more complicated that it needs to be, why not just have the Service receive the Intent from the AlamManager?
I understand that the Phone is guaranteed not to sleep while onReceive() is executing i.e. it wrapped with a wake lock. I'm not sure if the Service class offers any similar guarantees.
Is the any way to start the Service directly from an Alarm while still guaranteeing that the Phone will be woken from sleep and won't sleep until a wake lock can be acquired?
android.app.AlarmManager. This class provides access to the system alarm services. These allow you to schedule your application to be run at some point in the future.
This example demonstrates how do I use AlarmManager in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.
The way that AlarmManager works was changed in API level 19 to help save battery life. It was so that events could be batched. What this means is that set() and setRepeating() will be inexact on API 19+. In API versions before 19, you can just use set, which will schedule an alarm for the exact time.
This seems more complicated that it needs to be, why not just have the Service receive the Intent from the AlamManager?
Because Android will not guarantee that the device will stay awake long enough for a getService()
PendingIntent
to be invoked. The guarantee is only for a getBroadcast()
PendingIntent
-- Android ensures that the device will stay awake (via a WakeLock
) for the duration of your onReceive()
call.
Trust me, I wish we could skip it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With