Reputation: 31
I have this code in a BroadcastReceiver that should change a textview with the word "CHARGING" if the phone is plugged or with a Count Down Timer if it is not:
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();
}
}
My problem is if I start the app with the phone plugged I can see the word "CHARGING" in the textview, when I unplug the phone I can see the count down timer, but when I plug the phone again, I only see the word "Charging" a millisecond and then I see the count down timer again. And if I unplug the phone again, I see two count down timers at the same time in the same textview.
It is like I create a new count down timer every time I plug the phone without destroy the previous one.
Upvotes: 3
Views: 4301
Reputation: 2236
Oh ok, first of all, don't make CountDownTimer class like that
/* Declare a class level object */
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
}
}
then when you want to start countdown timer
myCountDownTimer = new MyCountDownTimer(
999999999999999999L, 15 * 1000);
myCountDownTimer.start();
and when you want to cancel that
if(myCountDownTimer!=null)
{
myCountDownTimer.cancel();
}
Upvotes: 3