有人能给出一个简单的例子,每秒钟更新一个文本框左右?

我想要制作一个飞行的球,并需要每秒计算/更新球的坐标,这就是为什么我需要某种计时器。

我从这里什么也得不到。


当前回答

您需要创建一个线程来处理更新循环,并使用它来更新文本区域。棘手的部分是只有主线程可以修改ui,所以更新循环线程需要通知主线程进行更新。这是使用处理程序完成的。

查看这个链接:http://developer.android.com/guide/topics/ui/dialogs.html# 点击标题为“Example ProgressDialog with a second thread”的部分。这是一个你需要做什么的例子,除了一个进度对话框而不是一个文本框。

其他回答

如果你已经有了时间。

public class Timer {
    private float lastFrameChanged;
    private float frameDuration;
    private Runnable r;

    public Timer(float frameDuration, Runnable r) {
        this.frameDuration = frameDuration;
        this.lastFrameChanged = 0;
        this.r = r;
    }

    public void update(float dt) {
        lastFrameChanged += dt;

        if (lastFrameChanged > frameDuration) {
            lastFrameChanged = 0;
            r.run();
        }
    }
}
import kotlin.concurrent.fixedRateTimer

val timer = fixedRateTimer("Tag", false, 1000, 2500) { /* Your code here */ }

Kotlin非常简单

我认为你可以用Rx方法来做:

 timerSubscribe = Observable.interval(1, TimeUnit.SECONDS)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Action1<Long>() {
                @Override
                public void call(Long aLong) {
                      //TODO do your stuff
                }
            });

然后取消这个:

timerSubscribe.unsubscribe();

接收定时器 http://reactivex.io/documentation/operators/timer.html

因为这个问题仍然从谷歌搜索吸引了很多用户(关于Android定时器),我想插入我的两个硬币。

首先,Timer类在Java 9中将被弃用(请阅读已接受的答案)。

官方建议的方法是使用ScheduledThreadPoolExecutor,它更有效,功能丰富,可以额外安排命令在给定延迟后运行,或定期执行。此外,它还提供了ThreadPoolExecutor的额外灵活性和功能。

下面是一个使用普通功能的示例。

创建执行器服务: final ScheduledExecutorService SCHEDULER = executors . newscheduleledthreadpool (1); 只需安排你的runnable: 最后未来< ?> future = SCHEDULER。schedule(可运行任务,长延迟,TimeUnit单元); 你现在可以使用future来取消任务或检查任务是否完成,例如: future.isDone ();

希望你会发现这对在Android中创建任务有用。

完整的例子:

ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
Future<?> sampleFutureTimer = scheduler.schedule(new Runnable(), 120, TimeUnit.SECONDS);
if (sampleFutureTimer.isDone()){
    // Do something which will save world.
}

对于想要在kotlin中这样做的人:

val timer = fixedRateTimer(period = 1000L) {
            val currentTime: Date = Calendar.getInstance().time
            runOnUiThread {
                tvFOO.text = currentTime.toString()
            }
        }

为了停止计时器,你可以使用这个:

timer.cancel()

这个函数有许多其他选项,请尝试一下