意图启动时停止计时器

时间:2017-02-18 07:41:02

标签: android android-intent

我做了一个倒数计时器,它在10秒内启动,当计时器在5秒内时,意图将执行,但计时器继续,然后当计时器完成另一个意图将执行...这是我的问题。 我想要的是当计时器在5秒内意图将执行并且计时器将停止并且没有其他意图执行。

public class MainActivity extends AppCompatActivity {
String timerStr;
int timerInt;
Intent intent;
Intent intent2;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    intent = new Intent(this, Main3Activity.class);
    intent2 = new Intent(this, Main2Activity.class);

    new CountDownTimer(10000, 1000){

        @Override
        public void onTick(long millisUntilFinished) {
            Log.i("Seconds left", String.valueOf(millisUntilFinished / 1000));
            timerStr = String.valueOf(millisUntilFinished / 1000);

            progress = Integer.parseInt(timerStr);
            Log.i("Timer: ", String.valueOf(progress));
            if (progress == 5){
                startActivity(intent2);    
            }
        }

        @Override
        public void onFinish() {
            Log.i("Done!","Countdown finished!");
            startActivity(intent);
        }
    }.start();

}

如何在意图启动时停止计时器?

2 个答案:

答案 0 :(得分:1)

我想你需要这个。 你的onTick方法应该是这样的:

@Override
    public void onTick(long millisUntilFinished) {
        Log.i("Seconds left", String.valueOf(millisUntilFinished / 1000));
        timerStr = String.valueOf(millisUntilFinished / 1000);

        progress = Integer.parseInt(timerStr);
        Log.i("Timer: ", String.valueOf(progress));
        if (progress == 5){
            startActivity(intent2);
            if(timer!=null){
            timer.cancel(); //stop the timer by call
}

希望这会有所帮助!!

答案 1 :(得分:0)

就这样做吧。将您的CountDownTimer存储在变量中,然后在cancel()时调用5s

public class MainActivity extends AppCompatActivity {
String timerStr;
int timerInt;
Intent intent;
Intent intent2;
CountDownTimer countDownTimer;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    intent = new Intent(this, Main3Activity.class);
    intent2 = new Intent(this, Main2Activity.class);

    coutDownTimer = new CountDownTimer(10000, 1000){

        @Override
        public void onTick(long millisUntilFinished) {
            Log.i("Seconds left", String.valueOf(millisUntilFinished / 1000));
            timerStr = String.valueOf(millisUntilFinished / 1000);

            progress = Integer.parseInt(timerStr);
            Log.i("Timer: ", String.valueOf(progress));
            if (progress == 5){
                startActivity(intent2);  
                countDownTimer.cancel();
            }
        }

        @Override
        public void onFinish() {
            Log.i("Done!","Countdown finished!");
            startActivity(intent);
        }
    }.start();

}