我希望在60秒后定期调用特定的代码补丁,以获取应用程序中的更新数据。我想知道我应该把代码放在主Android活动中。任何帮助将不胜感激 感谢
答案 0 :(得分:1)
您可以使用 Timer
类的Java util
包。它将允许您再次执行特定代码。再次定期。看看每5秒执行一次的example。
答案 1 :(得分:0)
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();
}
}
}
此“计时器”与活动生命周期相关联,请记住在Activity#onDestroy
中将其停在Activity#onPause
或更好。{{1}}。结帐Timer,ScheduledThreadPoolExecutor和TimerTask它们可能会更好地满足您的需求。
答案 2 :(得分:0)
在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);
请参阅此网站以获取更多信息。
http://www.vogella.com/articles/AndroidServices/article.html