如何在Android中销毁CountDownTimer?

时间:2014-05-15 12:24:27

标签: java android countdowntimer

我在BroadcastReceiver中有这个代码,如果手机插上电源,应该用“CHARGING”字样改变文本视图,如果不是,则用Count Down Timer改变:

       int chargePlug = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
        boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
        boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;


        TextView textView2 = (TextView) findViewById(R.id.textView2);
            TextView textView3 = (TextView) findViewById(R.id.textView3);


            String str = Boolean.toString(isCharging);
            textView2.setText(str);


            CountDownTimer aCounter = new CountDownTimer((long) timeleft, 1000) {
                 public void onTick(long millisUntilFinished) {

                    long seconds = millisUntilFinished / 1000;

                       mTextField.setText(String.format("%02d:%02d:%02d", seconds / 3600,
                                (seconds % 3600) / 60, (seconds % 60)));
                     }

                     public void onFinish() {
                         mTextField.setText("done!");
                     }
                  };


                if (usbCharge || acCharge ) {


                    textView3.setText("Charging");
                    mTextField.setText("CHARGING");


                        aCounter.cancel();
                        aCounter = null;


                }

                else {

                    textView3.setText("Not Charging");
                    mTextField.setText("NOT CHARGING");


                    aCounter.start();

                     }

                }

我的问题是,如果我在插入手机的情况下启动应用程序,我可以在textview中看到“充电”一词,当我拔下手机时,我可以看到倒计时器,但是当我再次插上手机时,我只能看到“充电”这个词一毫秒,然后我再次看到倒计时器。如果我再次拔掉电话,我会在同一文本视图中同时看到两个倒计时器。

就像我每次插上手机时都会创建一个新的倒计时器而不会破坏前一个。

1 个答案:

答案 0 :(得分:2)

哦,好吧,首先,不要像那样生成CountDownTimer类

/ *声明一个类级别对象* /

private MyCountDownTimer myCountDownTimer;

private class MyCountDownTimer extends CountDownTimer {

        public MyCountDownTimer(long millisInFuture,
                long countDownInterval) {
            super(millisInFuture, countDownInterval);
            // TODO Auto-generated constructor stub
        }

        @Override
        public void onTick(long millisUntilFinished) {

            //TODO some code here

        }

        @Override
        public void onFinish() {
            // TODO Auto-generated method stub

        }

    }

然后当你想要开始倒数计时器

myCountDownTimer = new MyCountDownTimer(
                999999999999999999L, 15 * 1000);

myCountDownTimer.start();

当你想要取消

if(myCountDownTimer!=null)
{

    myCountDownTimer.cancel();

}