1

I usually write this code to start a service with AlarmManager.

    intent = new Intent(getActivity(), someservice.class);
    pendingNotificationIntent = PendingIntent.getService(getActivity(), 0, intent, 0);
    alarm = (AlarmManager) getActivity().getSystemService(getActivity().ALARM_SERVICE);
    int interval = 30 * 1000;
    long now = Calendar.getInstance().getTimeInMillis();
    alarm.setRepeating(AlarmManager.RTC_WAKEUP, now, interval, pendingNotificationIntent);

My AsyncTask is a private class where I register AlarmManager object.

How can I call the AsyncTask instead of a service using AlarmManager object?

PS. If there is a better way to run AsyncTask every X seconds/minutes, please propose it!

sandalone
  • 41,141
  • 63
  • 222
  • 338
  • Just out of curiosity... why? Do you have a particular reason why you need an `AsyncTask` instead of a `Service`? – kabuko Jan 04 '13 at 19:34
  • @kabuko This task is supposed to work ONLY if app is open (UI is visible) so there is no purpose of using the service and double coding when I can simply call already existing `AsyncTask`. I know I can use `Timer`, but I am not sure if that is the proper way as it is not normally advised to use in repeating tasks. – sandalone Jan 05 '13 at 08:09

2 Answers2

1

Based upon munish-katoch's response, I have the following concrete solution.

Set an alarm:

Intent intent = new Intent(context, AlarmReceiver.class);

PendingIntent alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);

AlarmManager alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
alarmMgr.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, 
  SystemClock.elapsedRealtime() + 5 * 1000, 60 * 1000, alarmIntent);

The above code configures AlarmManager to fire at AlarmReceiver, which is defined as follows:

public class AlarmReceiver extends WakefulBroadcastReceiver {
  @Override
  public void onReceive(Context context, Intent intent) {  
    new MyAsyncTask.execute();
  }
}

In the event of an alarm AlarmReceiver starts MyAsyncTask.

Here be dragons

There are life cycle issues associated with instantiating an AsyncTask from a WakefulBroadcastReceiver, i.e., the above solution can lead to MyAsyncTask being killed prematurely. Moreover, threading rules are violated.

Community
  • 1
  • 1
user2768
  • 794
  • 8
  • 31
  • The following question is related: http://stackoverflow.com/questions/2750664/is-it-possible-to-use-asynctask-in-a-service-class/25298135 – user2768 Aug 14 '14 at 00:52
0

This is how you can do it:

1.) Define a static intent (intent1) and use it to pass to AlarmManager when setting time. So now when ever time, will lapse; AlarmManager will notify by sending intent1.

2.) On onReceive of BroadcastReceiver of intent1, start a AsyncTask. At end end of AsyncTask, set the next time for AlarmManager.

Munish Katoch
  • 517
  • 3
  • 6