首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何打破CountDownTimer

如何打破CountDownTimer
EN

Stack Overflow用户
提问于 2015-08-19 03:47:38
回答 3查看 929关注 0票数 1

我是一个机器人新手,我遇到了一个问题。

,这是我的问题:,我运行一个间隔为5s的CountDownTimer,运行时间为30。当它运行时,我为每个间隔做一个活动。如果活动返回正结果,我将停止计时器。如果计时器结束,我会宣布它为失败。我尝试了很多方法,但我无法完成我所需要的。

我不知道如何使用CountDownTimerTimer?也许你知道?

这是我的代码:

代码语言:javascript
复制
    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();
    }
   }
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2015-08-19 04:06:11

尝试使用Handler代替。SomeThing是这样的:

代码语言:javascript
复制
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;
    }
}

编辑如何为结果启动活动:

第一种定义:

代码语言:javascript
复制
private final int CODE_NEW_LOCATION = 1;

在Rubbable里面放了这样的东西:

代码语言:javascript
复制
 startActivityForResult(new Intent(MainActivity.this, LocationActivity.class), CODE_NEW_LOCATION);

在LocationActivity中定义返回值:

代码语言:javascript
复制
 boolean result;
 //define the result
 setResult(Activity.RESULT_OK);
票数 1
EN

Stack Overflow用户

发布于 2019-08-18 16:45:47

您可以在this.cancel();对象中使用: CountDownTimer。

票数 0
EN

Stack Overflow用户

发布于 2020-01-20 13:48:15

在您的函数onTick中,尝试检查标志(布尔停止;)并禁用计数器。示例:

代码语言:javascript
复制
boolean stop;

@Override
    public void onTick(long millisUntilFinished) {

    if (stop) { 
       stop = false;
       cancel();
    }

}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32086210

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档