我是android的新手,但遇到了问题。
这是我的问题:我以5秒的间隔运行CountDownTimer
30秒。在运行时,我会为每个间隔进行一次活动。如果活动返回了积极的结果,我将停止计时器。如果计时器结束,我会宣布失败。我尝试了很多方法,但是我无法完成我所需要的。
我不知道如何使用CountDownTimer
或Timer
?也许你呢?
这是我的代码:
public void StartTimeOutTimer() {
countDown timer = new countDown(30000, 5000);
timer.start();
}
public class countDown extends CountDownTimer{
ProgressDialog pd;
public countDown(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
pd = ProgressDialog.show(Activity_MapMain.this, "",
"Loading new location...", true, false);
}
@Override
public void onTick(long millisUntilFinished) {
//Do an activity get new location
//if OK stop CountDownTimer ;
}
@Override
public void onFinish() {
pd.cancel();
}
}
最佳答案
尝试改用Handler。像这样:
Handler handler;
boolean result;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
handler = new Handler();
handler.post(timerRunnable);
}
Runnable timerRunnable = new Runnable() {
int interval = 5000, period = 30000;
int count;
@Override
public void run() {
if (!result && count < period ) {
count += interval;
//call to the activity get new location with startActivityForResult()
handler.postDelayed(this, interval);
}
}
};
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK){
result = true;
}
}
编辑
如何开始活动以获得结果:
首先定义字段:
private final int CODE_NEW_LOCATION = 1;
在Rubbable里面放这样的东西:
startActivityForResult(new Intent(MainActivity.this, LocationActivity.class), CODE_NEW_LOCATION);
在LocationActivity内部,您定义返回值:
boolean result;
//define the result
setResult(Activity.RESULT_OK);
关于android - 如何打破CountDownTimer,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32086210/