"Innovation comes only from readily and seamlessly sharing information rather than hoarding it."- Tom Peters
Development Blog

Articles - Android entries

Starting Activity from Sleeping Device

Permissions Required

In order to wake up the device, you need to request the WAKE_LOCK permission. To do that, add this XML snippet into your AndroidManifest.xml.

<uses-permission android:name="android.permission.WAKE_LOCK" />

Waking up the Activity Using a Wake Lock

NOTE: I'm modifying the code found in Android - Creating an Alarm with AlarmManager.

Add this to your AlarmReceiverActivity:

private PowerManager.WakeLock wl;
...
public void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "My Tag");
        wl.acquire();
       ...
       ... //The rest of the onCreate() is still the same (for now)
}

protected void onStop() {
    super.onStop();
    wl.release();
}

So, what we're doing here is requesting a WAKE_LOCK from the operating system. This lock is a lock on CPU and must be released. That's why (in this case), I release the lock in the onStop for the activity. Feel free to move it to somewhere else, but you must be sure it gets released.

Android - Creating an Alarm with AlarmManager

There isn't a lot of good write-ups on how to use the AlarmManager, so here is an example that launches an Activity using the AlarmManager.

What's the AlarmManager used for?

The AlarmManager is used to schedule events or services at either a set time or a set interval. It's Android's "version" of the cron. In this case, we're going to set an alarm for five seconds after the app is launched.

What we're going to build

In order to use build this simple app, we're going to create only two classes. One will be for the Main Activity, and one will be for the Activity we want to launch with the Alarm. We will also have two simple layouts for each of the activities.