有人能给出一个简单的例子,每秒钟更新一个文本框左右?
我想要制作一个飞行的球,并需要每秒计算/更新球的坐标,这就是为什么我需要某种计时器。
我从这里什么也得不到。
有人能给出一个简单的例子,每秒钟更新一个文本框左右?
我想要制作一个飞行的球,并需要每秒计算/更新球的坐标,这就是为什么我需要某种计时器。
我从这里什么也得不到。
当前回答
因为这个问题仍然从谷歌搜索吸引了很多用户(关于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.
}
其他回答
我很惊讶,没有答案会提到RxJava2的解决方案。它真的很简单,提供了一个简单的方法来设置计时器在Android。
首先你需要设置Gradle依赖,如果你还没有这样做:
implementation "io.reactivex.rxjava2:rxjava:2.x.y"
(将x和y替换为当前版本号)
因为我们只有一个简单的,非重复的TASK,我们可以使用Completable对象:
Completable.timer(2, TimeUnit.SECONDS, Schedulers.computation())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(() -> {
// Timer finished, do something...
});
对于重复TASK,你可以用类似的方式使用Observable:
Observable.interval(2, TimeUnit.SECONDS, Schedulers.computation())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(tick -> {
// called every 2 seconds, do something...
}, throwable -> {
// handle error
});
Schedulers.computation()确保我们的计时器在后台线程上运行,. observveon (AndroidSchedulers.mainThread())意味着我们在计时器结束后运行的代码将在主线程上完成。
为了避免不必要的内存泄漏,您应该确保在Activity/Fragment被销毁时取消订阅。
你也可以使用动画器:
int secondsToRun = 999;
ValueAnimator timer = ValueAnimator.ofInt(secondsToRun);
timer.setDuration(secondsToRun * 1000).setInterpolator(new LinearInterpolator());
timer.addUpdateListener(new ValueAnimator.AnimatorUpdateListener()
{
@Override
public void onAnimationUpdate(ValueAnimator animation)
{
int elapsedSeconds = (int) animation.getAnimatedValue();
int minutes = elapsedSeconds / 60;
int seconds = elapsedSeconds % 60;
textView.setText(String.format("%d:%02d", minutes, seconds));
}
});
timer.start();
如果您还需要在UI线程上运行代码(而不是在计时器线程上),请查看博客:http://steve.odyfamily.com/?p=12
public class myActivity extends Activity {
private Timer myTimer;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
myTimer = new Timer();
myTimer.schedule(new TimerTask() {
@Override
public void run() {
TimerMethod();
}
}, 0, 1000);
}
private void TimerMethod()
{
//This method is called directly by the timer
//and runs in the same thread as the timer.
//We call the method that will work with the UI
//through the runOnUiThread method.
this.runOnUiThread(Timer_Tick);
}
private Runnable Timer_Tick = new Runnable() {
public void run() {
//This method runs in the same thread as the UI.
//Do something to the UI thread here
}
};
}
对于想要在kotlin中这样做的人:
val timer = fixedRateTimer(period = 1000L) {
val currentTime: Date = Calendar.getInstance().time
runOnUiThread {
tvFOO.text = currentTime.toString()
}
}
为了停止计时器,你可以使用这个:
timer.cancel()
这个函数有许多其他选项,请尝试一下
我用这种方法:
String[] array={
"man","for","think"
}; int j;
然后在onCreate下面
TextView t = findViewById(R.id.textView);
new CountDownTimer(5000,1000) {
@Override
public void onTick(long millisUntilFinished) {}
@Override
public void onFinish() {
t.setText("I "+array[j] +" You");
j++;
if(j== array.length-1) j=0;
start();
}
}.start();
解决这个问题很简单。