我在BroadcastReceiver中有此代码,如果插入了电话,则应使用“CHARGING”一词来更改文本视图;如果没有插入,则应使用“倒数计时器”:
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();
}
}
我的问题是,如果我在插入电话的情况下启动应用程序,则在文本视图中可以看到单词“CHARGING”,在拔出电话时,我可以看到倒数计时器,但是当我再次插入电话时,我只会看到单词“充电”一毫秒,然后我再次看到倒数计时器。而且,如果我再次拔下电话,我会在同一文本视图中同时看到两个倒数计时器。
就像我每次插入电话时都创建一个新的倒数计时器,而不会破坏前一个倒数计时器一样。
最佳答案
哦,好的,首先,不要像这样使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();
}