Reputation: 13
I have a timer in a thread waiting like 20 seconds before moving to a new activity, what I'm looking for is to show the time whatever decreasing or increasing in a textView in that while. here's my code:
Thread timer = new Thread() {
public void run() {
try {
sleep(ie);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
Intent i = new Intent(Activity.this, Menu.class);
if (ie == 20000) {
startActivity(i);
overridePendingTransition(R.anim.pushin, R.anim.pushout);
}
}
}
};
timer.start();
thanks for your assisstance
Upvotes: 0
Views: 39
Reputation: 1850
Camilo Sacanamboy's answer is the correct one. If you want to do this with a Thread, one solution might be like this:
final TextView status; //Get your textView here
Thread timer = new Thread() {
public void run() {
int time = 20000;
try {
while(time > 0){
time -= 200; //Or whatever you might like
final int currentTime = time;
getActivity().runOnUiThread(new Runnable() { //Don't update Views on the Main Thread
@Override
public void run() {
status.setText("Time remaining: " + currentTime / 1000 + " seconds");
}
});
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
Intent i = new Intent(Activity.this, Menu.class);
if (ie == 20000) {
startActivity(i);
overridePendingTransition(R.anim.pushin, R.anim.pushout);
}
}
}
};
timer.start();
Upvotes: 0
Reputation: 620
Try a CountDownTimer instead of a Thread:
CountDownTimer count = new CountDownTimer(20000, 1000)
{
int counter = 20;
@Override
public void onTick(long millisUntilFinished)
{
// TODO Auto-generated method stub
counter--;
textView.setText(String.valueOf(counter));
}
@Override
public void onFinish()
{
startActivity(i);
overridePendingTransition(R.anim.pushin, R.anim.pushout);
}
};
count.start();
Upvotes: 1