I am developing an Android app and in that I have a countdown timer
which onFinish()
does this -
double initial_time = 0.0;
double countup;
public void onFinish() {
startTimer();
}
public void startTimer(){
//Start the scheduled timer
Log.d("hi","crash app 0");
Early_Delay_Display.setText(R.string.Departure_Delay);
rootView.invalidate();
Timer timer = new Timer();
timer.scheduleAtFixedRate(
new java.util.TimerTask() {
@Override
public void run() {
Log.d("hi","crash app 1" + initial_time);
countup = 0.0 + initial_time;
Log.d("hi","crash app 2" + initial_time + "---------" + countup);
Early_Delay_Time.setText(String.valueOf(countup));
rootView.invalidate();
initial_time = initial_time + 0.5;
}
},
1000, 30000//delay,period
);
}
Basically using this timer, I want to display 0.5,1.0,1.5 for every 30 seconds but the app crashes.
The logs are -
crash app 0
crash app 1 0.0
crash app 2 0.0---------0.0
After this the app crashes
android中有一个特殊的CountDownTimer ,因此您可以像这里提到的那样使用它
我猜您的活动已被破坏,然后计时器使您的应用崩溃。
I found out the answer. You can never update the UI froma thread. Instead you could do this -
public void startUpCounting(){
//Start the scheduled timer
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
countup = 0.0 + initial_time;
Log.d("hi","crash app 2" + initial_time + "---------" + countup);
mHandler.obtainMessage(1).sendToTarget();
initial_time = initial_time + 0.5;
}
}, 0, 1000);
}
public Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
Early_Delay_Time.setText(String.valueOf(countup));
rootView.invalidate();
}
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.