Sevak.Avet
Sevak.Avet

Reputation: 121

How to run task by schedule in android?

I want to execute some task (e.g. show notification), by schedule, e.g.: 10:00 every day AND 11:00 every monday and etc., I can't use AlarmManager, because the time interval between tasks is different and I can't run task every N second. Can I specify a few tasks for AlarmManager? How I can do it and what I should use?

Upvotes: 0

Views: 147

Answers (1)

CommonsWare
CommonsWare

Reputation: 1007584

I can't use AlarmManager, because the time interval between tasks is different

Yes, you can.

One option is to use different alarms for different tasks. In your example, you would have one alarm for "10:00 every day" and a separate alarm for "11:00 every Monday".

Another option is to use a single alarm for whatever comes next, where it then does whatever your business logic is (e.g., remind the user of the event) and then schedules the next alarm for the next thing to occur. For example, using my time zone, it is 07:45 on a Saturday right now. Your app would have an AlarmManager alarm to get control at 10:00 ("10:00 every day"). When that alarm is invoked, it would then schedule an AlarmManager alarm for 10:00 Sunday ("10:00 every day"). 10:00 on Sunday, it would then schedule an alarm for 10:00 Monday ("10:00 every day"). 10:00 on Monday, it would then schedule an alarm for 11:00 Monday ("11:00 every monday"). 11:00 on Monday, it would then schedule an alarm for 10:00 Tuesday. And so on.

If there are only a couple of rules, I would go with the first option. If there could be N possible rules, I would go with the second option, so as not to flood AlarmManager.

Can I specify a few tasks for AlarmManager?

Yes. Make sure that the PendingIntent objects are distinct. The easiest way to do that is to use unique values for the requestCode parameter to PendingIntent factory methods like getBroadcast().

Upvotes: 1

Related Questions