38

我想每 5 秒后重复调用一个方法,并且每当我想停止该方法的重复调用时,我可以停止或重新启动该方法的重复调用。

这是我真正想要实现的一些示例代码。请在这方面帮助我,我将非常感谢你。

private int m_interval = 5000; // 5 seconds by default, can be changed later
private Handler m_handler;

@Override
protected void onCreate(Bundle bundle)
{
  ...
  m_handler = new Handler();
}

Runnable m_statusChecker = new Runnable()
{
     @Override 
     public void run() {
          updateStatus(); //this function can change value of m_interval.
          m_handler.postDelayed(m_statusChecker, m_interval);
     }
};

public void startRepeatingTask()
{
    m_statusChecker.run(); 
}

public void stopRepeatingTask()
{
    m_handler.removeCallbacks(m_statusChecker);
}  
4

5 回答 5

92

使用此设置重复任务:

//Declare the timer
Timer t = new Timer();
//Set the schedule function and rate
t.scheduleAtFixedRate(new TimerTask() {

    @Override
    public void run() {
        //Called each time when 1000 milliseconds (1 second) (the period parameter)
    }

},
//Set how long before to start calling the TimerTask (in milliseconds)
0,
//Set the amount of time between each execution (in milliseconds)
1000);

如果您想取消任务,只需调用t.cancel()这里t是您的Timer对象

您还可以查看您的答案下方的评论,他们提供了有关此的简要信息。

于 2013-08-21T09:29:04.893 回答
7

在方法中使用Handler 。onCreate()它的postDelayed()方法导致Runnable被添加到消息队列并在经过指定的时间量后运行(在给定的示例中为 0)。然后这将在固定的时间速率(本例中为 1000 毫秒)后自行排队。

请参阅此代码:

public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    android.os.Handler customHandler = new android.os.Handler();
    customHandler.postDelayed(updateTimerThread, 0);
}

private Runnable updateTimerThread = new Runnable()
{
    public void run()
    {
        //write here whaterver you want to repeat
        customHandler.postDelayed(this, 1000);
    }
};
于 2014-04-05T09:49:35.683 回答
5

使用 TimerTask 在特定时间间隔后调用

    Timer timer = new Timer();
    timer.schedule(new UpdateTimeTask(),1, TimeInterval);

  class UpdateTimeTask extends TimerTask {

        public void run() 
           {        
            // do stufff
           }

        }
于 2013-08-21T09:29:28.817 回答
2

在Handler的帮助下以 Android 的方式进行。

声明一个不泄漏内存的 Handler

/**
     * Instances of static inner classes do not hold an implicit
     * reference to their outer class.
     */
    private static class NonLeakyHandler extends Handler {
        private final WeakReference<FlashActivity> mActivity;

        public NonLeakyHandler(FlashActivity activity) {
            mActivity = new WeakReference<FlashActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            FlashActivity activity = mActivity.get();
            if (activity != null) {
                // ...
            }
        }
    }

声明一个处理你的任务的runnable

   private Runnable repeatativeTaskRunnable = new Runnable() {
        public void run() {
            new Handler(getMainLooper()).post(new Runnable() {
                @Override
                public void run() {

         //DO YOUR THINGS
        }
    };

在 Activity/Fragment 中初始化处理程序对象

//Task Handler
private Handler taskHandler = new NonLeakyHandler(FlashActivity.this);

固定时间间隔后重复任务

taskHandler.postDelayed(repeatativeTaskRunnable , DELAY_MILLIS);

停止重复

taskHandler .removeCallbacks(repeatativeTaskRunnable);

于 2017-08-10T04:21:57.477 回答
0

您必须将此代码放入要每 5 秒调用一次的活动中

final Runnable tarea = new Runnable() {   public void run() {
hola_mundo();//the operation that you want to perform }}; 
ScheduledExecutorService timer = Executors.newSingleThreadScheduledExecutor();
timer.scheduleAtFixedRate(tarea, 5, 5, TimeUnit.SECONDS);
于 2018-03-21T19:27:35.630 回答