0

我想在 60 秒后定期调用特定的代码补丁,以获取应用程序中的更新数据。我想知道我应该将代码放在主要 Android 活动中的哪个位置。任何帮助将不胜感激谢谢

4

3 回答 3

1

您可以使用Java包Timer的 Class 。util它将允许您定期再次执行特定代码。查看每 5 秒执行一次的示例。

于 2013-03-12T07:07:27.987 回答
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 生命周期相关联,记得Activity#onDestroyActivity#onPause. 还可以查看TimerScheduledThreadPoolExecutorTimerTask,它们可能更适合您的需求。

于 2013-03-12T07:37:31.330 回答
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

于 2013-03-12T07:43:02.547 回答