Skip to content

Instantly share code, notes, and snippets.

@anitaa1990
Created May 16, 2018 17:24
Show Gist options
  • Save anitaa1990/7d52effe43c90031bcd8b4906158ebba to your computer and use it in GitHub Desktop.
Save anitaa1990/7d52effe43c90031bcd8b4906158ebba to your computer and use it in GitHub Desktop.
public class TimerTaskReferenceLeakActivity extends Activity {
private CountDownTimer countDownTimer;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
startTimer();
}
public void cancelTimer() {
if(countDownTimer != null) countDownTimer.cancel();
}
private void startTimer() {
countDownTimer = new CountDownTimer(1000, 1000) {
@Override
public void onTick(long millisUntilFinished) {
final int secondsRemaining = (int) (millisUntilFinished / 1000);
//update UI
}
@Override
public void onFinish() {
//handle onFinish
}
};
countDownTimer.start();
}
/*
* Fix 1: Cancel Timer when
* activity might be completed
* */
@Override
protected void onDestroy() {
super.onDestroy();
cancelTimer();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment