How can repeating AlarmManager start AsyncTask?

自作多情 提交于 2019-12-01 12:21:02

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.

user2768

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!