Reputation: 87
I want to call a specific patch of code regularly after 60 seconds to get the updated data in the application. I am wondering where i should put the code in the Main Android activity. Any help will be appreciated thanks
Upvotes: 0
Views: 790
Reputation: 800
import android.os.Handler;
public class ExecuteEveryMinuteExample {
private static final int DELAY_IN_MILLIS = 60000;
private final Handler handler;
private final Runnable task;
public ExecuteEveryMinuteExample(Handler handler, Runnable runnable) {
this.handler = handler;
this.task = new Task(runnable);
}
public void start() {
handler.postDelayed(task, DELAY_IN_MILLIS);
}
public void stop() {
handler.removeCallbacks(task);
}
private class Task implements Runnable {
private Runnable task;
private Task(Runnable runnable) {
this.task = runnable;
}
@Override
public void run() {
task.run();
start();
}
}
}
This "timer" is associated with Activity lifecycle, remember to stop it in Activity#onDestroy
or better in Activity#onPause
. Also checkout Timer, ScheduledThreadPoolExecutor and TimerTask they may suit your needs better.
Upvotes: 0
Reputation: 706
use services and broadcast receivers in android.
// Restart service every 30 seconds
private static final long REPEAT_TIME = 1000 * 30;
@Override
public void onReceive(Context context, Intent intent) {
AlarmManager service = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, MyStartServiceReceiver.class);
PendingIntent pending = PendingIntent.getBroadcast(context, 0, i,
PendingIntent.FLAG_CANCEL_CURRENT);
Calendar cal = Calendar.getInstance();
// Start 30 seconds after boot completed
cal.add(Calendar.SECOND, 30);
//
// Fetch every 30 seconds
// InexactRepeating allows Android to optimize the energy consumption
service.setInexactRepeating(AlarmManager.RTC_WAKEUP,
cal.getTimeInMillis(), REPEAT_TIME, pending);
refer this site for more information.
http://www.vogella.com/articles/AndroidServices/article.html
Upvotes: 0