在 android 中,如果单击按钮,我希望倒计时从 30 开始,倒计时到 0。我使用基本倒计时方法创建了一个代码,但问题是如果 Activity 或应用程序关闭,它不会继续倒计时。
我想要做的是让 Activity 或只是倒计时在后台继续滴答作响,直到达到 0,此时它将变量 B 更改为值 1。
我已经扩展了我原来的模型,认为我可以比较从单击按钮 + 30 秒到再次调用 Activity 的日期时间。但到目前为止,我在 Android 中比较两个日期时间时遇到了困难。
有什么帮助吗?
最佳答案
您可能想要的是在后台运行的异步任务。像这样的东西:
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;
}
关于java - 每 30 秒给一个变量赋值 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7397009/