Search code examples
javaandroidservicealarmmanagerwakelock

Android: Using wakelock in service triggered by alarmmanager


In my application, I've got an alarm which triggers a service which downloads information from the internet and shows a notification.

Here's a simplified version of my code:

MyActivity contains this:

            Calendar cal = Calendar.getInstance();
            cal.add(Calendar.SECOND, 20);
            Intent intent = new Intent(this, AlarmService.class);
            PendingIntent pendingIntent = PendingIntent.getService(this, 0, intent, 0);
            AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 20000, pendingIntent);

And AlarmService looks like this:

public class AlarmService extends Service {

    @Override
    public void onCreate() {

        new myAsyncTask().execute();

    }

    private class myAsyncTask extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... args) {

            //Download stuff

            return null;
        }

        @Override
        protected void onPostExecute(Void arg) {
            //Show notification
        }
    }
}

I don't really understand when to use wake-locks, so my question: in this case, should I use a wake-lock and if so, where should I start and stop it?

Thanks in advance


Solution

  • Yes, you will need to use a WakeLock to ensure that your service can finish its work.

    If using an IntentService meets your design requirements, I would take a look at WakefulIntentService. It manages the alarms and the WakeLocks on your behalf and is easy to set up. The WakeLock is acquired when the alarm fires, and the WakefulIntentService library takes care of releasing it when the service is finished.

    If you go this route, you won't want to use AsyncTask -- you'll need to keep the service actively busy (in its doWakefulWork() method) in order to hold the WakeLock.