如何打破CountDownTimer

时间:2015-08-19 03:47:38

标签: android timer countdowntimer

我是Android的新手,而且我遇到了问题。

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

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

这是我的代码:

    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();
    }
   }

2 个答案:

答案 0 :(得分:1)

尝试使用Handler。像这样的SomeThing:

expiration_min = input("Enter minute \n(Enter 'none' if there is no minute): ").rstrip(),

expiration_hour = input("Enter hour \n(Enter 'none' if there is no hour): ").rstrip(),

修改 如何启动结果活动:

首先定义提交:

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;
    }
}

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

private final int CODE_NEW_LOCATION = 1;

在LocationActivity中,您可以定义返回值:

 startActivityForResult(new Intent(MainActivity.this, LocationActivity.class), CODE_NEW_LOCATION);

答案 1 :(得分:0)

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