I have implemented the timer functionality in android app, I able to finish the timer from other local methods by calling timerObject.cancel()
. Its working perfect
if using RXJava2. this code can help you.
public abstract class CountDownTimer {
private TimeUnit timeUnit;
private Long startValue;
private Disposable disposable;
public CountDownTimer(Long startValue,TimeUnit timeUnit) {
this.timeUnit = timeUnit;
this.startValue = startValue;
}
public abstract void onTick(long tickValue);
public abstract void onFinish();
public void start(){
io.reactivex.Observable.zip(
io.reactivex.Observable.range(0, startValue.intValue()), io.reactivex.Observable.interval(1, timeUnit), (integer, aLong) -> {
Long l = startValue-integer;
return l;
}
).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer() {
@Override
public void onSubscribe(Disposable d) {
disposable = d;
}
@Override
public void onNext(Long aLong) {
onTick(aLong);
}
@Override
public void onError(Throwable e) {
e.printStackTrace();
}
@Override
public void onComplete() {
onFinish();
}
});
}
public void cancel(){
if(disposable!=null) disposable.dispose();
}
}
using:
public class MainActivity extends AppCompatActivity {
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.start_activity);
new CountDownTimer(10L, TimeUnit.SECONDS) {
@Override
public void onTick(long tickValue) {
Log.d("CountDown", "Remaining: " + tickValue);
// cancel();
}
@Override
public void onFinish() {
Log.d("CountDown", "The End!! ");
}
}.start();
}
}
the owner of the code https://gist.github.com/chemickypes/fa3b7fc5b5a00a3ce37fee5815018702