简体   繁体   English

Android-每单位时间执行动作

[英]Android - Perform Action Every Unit of Time

This is more of a question of ignorance than inability. 这更多的是无知而不是无能。 I am trying to build a timer application, but have found the CountDownTimer object too inaccurate for my purposes. 我正在尝试构建计时器应用程序,但是发现CountDownTimer对象对于我的目的而言是不准确的。 Thus, I want to manually create the timer by just ticking every unit of time and performing some kind of action on each tick (without necessarily counting down to anything, as I will handle this manually) - is there a built-in object to do this (other than CountDownTimer), or do I have to use threads/sleeps? 因此,我想通过仅勾选每个时间单位并在每个刻度上执行某种操作来手动创建计时器(不必倒数,因为我将手动处理)-是否有内置对象要做这个(除CountDownTimer之外),还是我必须使用线程/睡眠?

Use a Handler and the postDelayed() method. 使用HandlerpostDelayed()方法。 Accurate and easy to use. 准确且易于使用。 You just have to keep putting the callback in after every loop, but that's not too onerous, and lets you adjust the interval as you see fit. 您只需要在每个循环之后继续放置回调即可,但这并不太麻烦,并且可以根据需要调整时间间隔。

Handler timeThing = new Handler();    
Runnable timedWorker = new Runnable {
    public void run(){
        // Do work
        timeThing.postDelayed(this, 10000); // do it again later
    }
};
timeThing.postDelayed(timedWorker, 10000);

Use AsyncTask and Thread.sleep() : 使用AsyncTaskThread.sleep()

AsyncTask task=new AsyncTask<Void,Void,Void>() {
    @Override
    protected Void doInBackground(Void... params) {
        while (!isCancelled()) {
            try {
                Thread.sleep(1000);
                publishProgress();
            } catch (InterruptedException e) {
                break;
            }
        }
        return null;
    }

    @Override
    protected void onProgressUpdate(Void... values) {
        //do something here    
    }
};
//task.execute(); to start
//task.cancel(); to stop

Your onProgressUpdate() will be called every N seconds (1000 in this example). 您的onProgressUpdate()将每N秒(在此示例中为1000 onProgressUpdate()被调用。

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

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