gpt4 book ai didi

java - CountdownTimer 崩溃应用程序。尝试更新 UI 线程

转载 作者:行者123 更新时间:2023-11-30 00:29:21 25 4
gpt4 key购买 nike

我希望倒数计时器在一个单独的线程上,并让它在每次滴答时更新 UI。每次我点击启动时,应用程序都会关闭,并且我会收到“应用程序已停止”错误消息。

public class Activity_MultiplayerGame extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity__multiplayer_game);
}

public void btnStart_onClick(View view){
CountDownTimer timer = new CountDownTimer(15000, 1000){

@Override
public void onTick(final long millisUntilFinished) {
runOnUiThread(new Runnable() {
@Override
public void run() {
TextView countdownText = (TextView) findViewById(R.id.countdown);
Integer timeUntilFinished = (int) millisUntilFinished/1000;
countdownText.setText(timeUntilFinished);
}
});
}

@Override
public void onFinish() {
TextView countdownText = (TextView) findViewById(R.id.countdown);
countdownText.setText("Finished");
}
};

timer.start();
}
}

我假设创建 CountDownTimer 会为其提供自己的线程?

最佳答案

你可以使用 Handler 。我给你写了一个例子

此代码每隔一秒增加一个计数器,并在 textView显示和更新计数器值。

public class MainActivity extends Activity {


private Handler handler = new Handler();
private TextView textView;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.text);
startTimer();
}


int i = 0;
Runnable runnable = new Runnable() {
@Override
public void run() {
i++;
textView.setText("counter:" + i);
startTimer();
}
};

public void startTimer() {
handler.postDelayed(runnable, 1000);
}

public void cancelTimer() {
handler.removeCallbacks(runnable);
}

@Override
protected void onStop() {
super.onStop();
cancelTimer();
}
}

关于java - CountdownTimer 崩溃应用程序。尝试更新 UI 线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44748521/

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