In android if a button is clicked i want a countdown to start from 30 and countdown to 0. I created a code with a basic countdown method but the problem is it doesn't continue to countdown if the activity or application closes.
What i want to do is for the activity or just the countdown to continue ticking down in the background until it hits 0 in which it'll change variable B to the value of 1.
I have expanded from my original model thinking i could compare dates times from when the button was clicked + 30 seconds to when the activity is called up upon again. But so fa开发者_运维技巧r i have come to a stump in comparing two datetimes in android.
Any help?
What you likely want is an async task to run in the background. Something like:
private class JohnnysPollTask extends AsyncTask<Integer, Void, Integer> {
/**
* The system calls this to perform work in a worker thread and delivers
* it the parameters given to AsyncTask.execute()
*/
protected Integer doInBackground(Integer... millis) {
try {
int waited = 0;
int duration = 30000;
while (waited < duration) {
Thread.sleep(1000);
waited += 1000;
if (waited>=duration) {
b=1;
break;
}
}
} catch (InterruptedException e) {
// do nothing
}
return 1;
}
Implement CountDownTimer
inside service
.
You could try using a service instead of an activity.
精彩评论