简体   繁体   English

每秒执行一次方法

[英]Execute method every second

I want to execude some code every second in android, but I'd like to do is in one thread (main thread). 我想在android中每秒执行一些代码,但是我想在一个线程(主线程)中执行。 So far I have this: 到目前为止,我有这个:

locationTimer = new Timer("locationTimer", false);
locationTimer.schedule(new LocationCheckerTask(this), 0, 1000);

public class LocationCheckerTask extends TimerTask {
    private GeoWatcher watcher;

    public LocationCheckerTask(Context context) {
        watcher = new GeoWatcher(context);
    }

    @Override
    public void run() {
        // funky stuff
    }
}

Unfortunately, Timer class runs it's tasks on another thread. 不幸的是, Timer类在另一个线程上运行它的任务。 Why I want to do this in a single thread? 为什么我要在单个线程中执行此操作? Code in run() method will be executing really fast, so I figured I don't need another thread for it. run()方法中的代码将非常快地执行,因此我认为不需要其他线程。 What I want to do is to construct separate threads in run() method based on condition calculated every second. 我想做的是基于每秒计算的条件在run()方法中构造单独的线程。 So instead of having child thread constructing another threads, I'd like to do this on the main one. 因此,与其让子线程构造另一个线程,不如在主线程上执行此操作。

You can do this with Handler 您可以使用处理程序执行此操作

public class Job implements Runnable{
    private Handler handler;

    public Job () {
       handler = new Handler(Looper.getMainLooper());
       loop();
    }

    @Override
    public void run() {
        // funky stuff
        loop();
    }

    private void loop() {
        handler.postDelayed(this, 1000);
    }
}

use runOnUiThread(Runnable) method of Activity to run the task in UI Thread 使用runOnUiThread(Runnable)方法在UI线程中运行任务

public class LocationCheckerTask extends TimerTask {
    private GeoWatcher watcher;

    public LocationCheckerTask(Context context) {
        watcher = new GeoWatcher(context);
    }

    @Override
    public void run() {
        runOnUiThread(new Runnable() {

            @Override
            public void run() {
                // funky stuff
            }
        });
    }
}

处理程序是此类任务的理想选择(不要尝试将TimerTask + runOnUiThread组合在一起-它无用,因为它在后台使用了处理程序)

private Runnable fiveSecondRunnable = new Runnable() {

    @Override
    public void run() {
        if (count5 < 0) {
            switchT030Sec();
        } else {
            tvSec5.setText(""+count5);
            Log.v("5sec set", "yes");
            count5--;
            man.postDelayed(this, 1000);
        }

    }
};

and start it by calling 并通过调用开始

man.post(fiveSecondRunnable);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM