What is the best way to schedule task in android?

2019-09-19 17:46发布

问题:

My project requirement is to schedule multiple tasks very frequently at exact time with delay between 0-5 seconds. What is the best way to schedule tasks for this purpose? Below are the options I considered: 1. Alarm Manager : Using Alarm Manager I have observed alarm does not schedule below 5 seconds. Even if I am passing 3 seconds time, alarm broadcasts after 5 seconds. Below is my code :

int requestCode = 101;
int delayTime = 3000L;

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

PendingIntent pendingIntent = PendingIntent.getBroadcast(context, requestCode, intent , PendingIntent.FLAG_ONE_SHOT);

AlarmManager alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
alarmMgr.setExact(AlarmManager.RTC_WAKEUP, delayTime, pendingIntent);
  1. Job Scheduler : I have read that this approach is not good for critical tasks and for exact time scheduling. And I need exact alarm scheduling for critical tasks.

Please point out other options as well.

回答1:

The best way I found is using Handler. And schedule tasks using postAtTime(Runnable r, long uptimeMillis) method.

For more info see : http://developer.android.com/reference/android/os/Handler.html