如何在android中固定一段时间后重复任务?

时间:2013-08-21 09:25:35

标签: java android

我想在每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);
}  

5 个答案:

答案 0 :(得分:74)

使用以下方法设置重复任务:

//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对象

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

答案 1 :(得分:6)

onCreate()方法中使用Handler。其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);
    }
};

答案 2 :(得分:5)

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

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

  class UpdateTimeTask extends TimerTask {

        public void run() 
           {        
            // do stufff
           }

        }

答案 3 :(得分:2)

Handler的帮助下以Android的方式完成。

声明does not leak Memory

的处理程序
/**
     * 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);

答案 4 :(得分: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);