我是一个机器人新手,我遇到了一个问题。
,这是我的问题:,我运行一个间隔为5s的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();
}
}发布于 2015-08-19 04:06:11
尝试使用Handler代替。SomeThing是这样的:
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);发布于 2019-08-18 16:45:47
您可以在this.cancel();对象中使用: CountDownTimer。
发布于 2020-01-20 13:48:15
在您的函数onTick中,尝试检查标志(布尔停止;)并禁用计数器。示例:
boolean stop;
@Override
public void onTick(long millisUntilFinished) {
if (stop) {
stop = false;
cancel();
}
}https://stackoverflow.com/questions/32086210
复制相似问题