简体   繁体   中英

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). 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. 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. What I want to do is to construct separate threads in run() method based on condition calculated every second. 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

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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