Android:定期执行代码

时间:2012-04-18 10:34:55

标签: android multithreading

我需要定期执行一些代码(连接到服务器并每分钟从MySQL数据库中提取数据)。为此,我有一个Sync类:

public class Sync {

    static private Handler handler = new Handler();
    Runnable task;

    public Sync(Runnable task, long time) {
        this.task = task;
        handler.removeCallbacks(task);
        handler.postDelayed(task, time);
    }
}

在我的活动中我有:

public void onCreate(Bundle savedInstanceState) {
    ...
    Sync sync = new Sync(call,60*1000);
    ...
}

final private Runnable call = new Runnable() {
    public void run() {
    //This is where my sync code will be, but for testing purposes I only have a Log statement
    Log.v("test","this will run every minute");
    }
};

我用较短的时间进行测试,但它只运行一次。当它第一次记录消息时,它也是最后一次。有谁看到我在这里做什么?谢谢!

5 个答案:

答案 0 :(得分:51)

您可以使用以下代码执行此操作, 希望它有所帮助!

final Handler handler = new Handler(); 
Runnable runnable = new Runnable() { 

    @Override 
    public void run() { 
        try{
            //do your code here
        }
        catch (Exception e) {
            // TODO: handle exception
        }
        finally{
            //also call the same runnable to call it at regular interval
            handler.postDelayed(this, 1000); 
        }
    } 
}; 

//runnable must be execute once
handler.post(runnable);

答案 1 :(得分:8)

首先,您必须全局声明处理程序 其次,你必须在runnable中再次使用post Delay方法再次触发它。

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Sync sync = new Sync(call,60*1000);

    }
    final private Runnable call = new Runnable() {
        public void run() {
        //This is where my sync code will be, but for testing purposes I only have a Log statement
        Log.v("test","this will run every minute");
        handler.postDelayed(call,60*1000);
        }
    };
    public final Handler handler = new Handler();
    public class Sync {


        Runnable task;

        public Sync(Runnable task, long time) {
            this.task = task;
            handler.removeCallbacks(task);
            handler.postDelayed(task, time);
        }
    }


}

答案 2 :(得分:3)

handler.postDelayed(task, time);只执行一次,如果您希望代码定期触发,我建议使用TimerTimerTask代替Handler和{ {1}}。

Runnable可设置为每x秒运行一次,或以固定周期运行,例如x秒 - 无论上次运行多长时间。

答案 3 :(得分:1)

      private void doSomethingRepeatedly() {
      timer.scheduleAtFixedRate( new TimerTask() {
            public void run() {

                  try{

                   //Your code

                  }
                  catch (Exception e) {
                      // TODO: handle exception
                  }

             }
            }, 0, 10000);
                     }

答案 4 :(得分:1)

另一种方法,使用ScheduledExecutorService' scheduleAtFixedRate

private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

public void beepEvery10Seconds() {
     final Runnable beeper = new Runnable() {
       public void run() { System.out.println("beep"); }
     };
     final ScheduledFuture<?> beeperHandle = scheduler.scheduleAtFixedRate(beeper, 0, 10, SECONDS);
}