开发者

Best way to set repeating task

开发者 https://www.devze.com 2023-01-22 17:36 出处:网络
i have a method in my app that i want to be called repeatedly depending on what the user chooses. like if every hour is chosen by the user, the activity fires a method that is being called every hour.

i have a method in my app that i want to be called repeatedly depending on what the user chooses. like if every hour is chosen by the user, the activity fires a method that is being called every hour. i would like to know the best way to schedule this repeated task.

i have been experimenting with Timers开发者_开发百科 and Timer task, but for some reason it doesn't not seem to work when i use the java calendar class with it, like this:

    Calendar c1 = Calendar.getInstance();
          c1.add(Calendar.SECOND, 30);    
  updateTimer.scheduleAtFixedRate(cleanCompletedCache, c1.getTimeInMillis(),hour );

and from what i have been reading, Handlers are not suitable for this multi-repeating task. would i have to use an alarm manager for this and why won't the above code execute correctly? thanks


You want the AlarmManager and it's setRepeating or setInexactRepeating calls.

There you schedule an Intent to be delivered to your application, and write an intent receiver to process it. This way, the activation of your application is entirely the responsibility of the Android system, and your application does not need to run for the entire hour it is just waiting to activate.

If, for some odd reason, you would need your code running between timer invocations, you need to keep a background service running, but you'd still use AlarmManager to get the wakeup.

0

精彩评论

暂无评论...
验证码 换一张
取 消