gpt4 book ai didi

java - 性能 - 从计时器线程更新 UI,而不阻塞 UI 线程

转载 作者:行者123 更新时间:2023-12-01 18:11:20 26 4
gpt4 key购买 nike

我是 android 新手,一直在阅读一些有关工作线程的内容,并且不会阻塞 UI 线程。我正在玩一个简单的计时器应用程序,它启动一个线程,在创建 Activity 时每秒更新一个 TextView 。所以我的问题是,现在最好的方法是什么?下面的两个例子都可以工作,但是有更好的(更高效/更Android)的方法吗?

    final Handler handler = new Handler();

handler.postDelayed(new Runnable() {
@Override
public void run() {
seconds++;
runOnUiThread(new Runnable() {
@Override
public void run() {
secondsTextView.setText(seconds);
}
});
handler.postDelayed(this, 1000);
}
}, 1000);

    new Thread(){
@Override
public void run(){
try{
while(!isInterrupted()){
Thread.sleep(1000);
runOnUiThread(new Runnable() {
@Override
public void run() {
seconds++;
secondsTextView.setText(seconds);
}
});
}
}catch(Exception e){
Log.e("Activity1", e.toString());
}
}
}.start();

最佳答案

更有效的方法是:

    timeOnTextView.postDelayed(new Runnable() {
@Override
public void run() {
seconds++;
timeOnTextView.postDelayed(this, 1000);
}
}, 1000);

传递给 postDelayed()Runnablerun() 在主应用程序线程上调用,因此您不需要使用runOnUiThread()

由于 postDelayed() 是在 View 上实现的,因此您不需要 Handler

关于java - 性能 - 从计时器线程更新 UI,而不阻塞 UI 线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32792167/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com