Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wake Service directly from AlarmManager

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?

like image 959
alexbirkett Avatar asked Sep 16 '11 11:09

alexbirkett


People also ask

What is AlarmManager in Android?

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.

How do I use alarm Manager?

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.

In which API level did inexact timing become the default for AlarmManager?

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.


1 Answers

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.

like image 108
CommonsWare Avatar answered Oct 18 '22 20:10

CommonsWare