Our Blog

Let’s make an Android Alarm Service, Part 1

Check out the finished project here: https://play.google.com/store/apps/details?id=com.UpstageInteractive.VibratingWatch

In this tutorial, we’ll cover:

  • Saving battery life by scheduling a repeating Service rather than keeping the activity running constantly
  • Creating an ongoing Notification
  • Reading the system’s time
  • Controlling vibration

Ok, Let’s get started!

I’m going to assume you’ve already created an empty Android application, and have a MainActivity.java ready to go. Also, let it be known that I’m the kind of developer who does Import statements as I need them, so even though they go at the beginning of the code, they’re not at the beginning of this tutorial.

First, make yourself a new Service. (in Eclipse, that’s File > New > Class)

I’ve called mine MyService. Your MyService.java should now look like this:


package com.YourName.YourPackageName;

import android.app.Service;

public class MyService extends Service {

}

Next, let’s make it do absolutely nothing, and then close.

//[...]

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.v("MyService","Yup, the service ran");
        return Service.START_NOT_STICKY;
    }

//[...]

START_NOT_STICKY tells the system not to recreate the Service if it closes. This is key to minimizing our battery/cpu usage. The Service will run when we schedule it, and then go away.

Great, now hop back over to MainActivity.java.

We’re going to be using AlarmManager.setRepeating(), which takes four arguments: int type, long triggerAtMillis, long intervalMillis, PendingIntent operation

Type is one of four options. Via the Android Docs:

ELAPSED_REALTIME—Fires the pending intent based on the amount of time since the device was booted, but doesn’t wake up the device. The elapsed time includes any time during which the device was asleep.
ELAPSED_REALTIME_WAKEUP—Wakes up the device and fires the pending intent after the specified length of time has elapsed since device boot.
RTC—Fires the pending intent at the specified time but does not wake up the device.
RTC_WAKEUP—Wakes up the device to fire the pending intent at the specified time.

For our purposes, we want RTC_WAKEUP.

The other arguments of AlarmManager.setRepeating() are self-explanatory. intervalMillis is the interval at which to call the Intent, and triggerAtMillis is the time from now (in milliseconds)

Later on, we’ll be scheduling the service after clicking on a Button, but for now, just stick the code inside onCreate().

Stay tuned for part 2, in which the app starts to do something useful!

Comments ( 0 )