How to create a lifecycle aware custom class in Android.

Search for a command to run...

No comments yet. Be the first to comment.
hey, Android help me get data from my other app

Bit manipulation to set multiple properties to a single field.

Why Powermockito.whenNew() is not enough.

Post inspired by RecyclerCalendarAndroid Lib RecyclerView The theory is simple, we need each day of the calendar rendered as one cell of the RecyclerView. To achieve this, we need to first prepare list of all dates, but there is a problem, we are mi...

We all know, each component in Android has its lifecycle, be it Activity, Fragment or Service. Each component gets created and destroys (and a few other stages in between).
To create a custom class that is lifecycle aware inherently, we can use a set of libraries provided under jetpack lifecycle.
For example, I want to create a timer, which invokes a method on each interval, and also, it should be lifecycle aware so it dies with its owner.
Firstly, we will create an interface that extends LifecycleOwner, this interface is implemented all new androidx. components.
public interface OnIntervalListener extends LifecycleOwner {
void onTimerInterval();
}
Now, we create out actual timer,
/**
* @implNote An implementation of lifecycle aware timer, can be attached to Activity or fragment
*/
public class LifecycleAwareTimer implements Runnable, DefaultLifecycleObserver {
public interface OnIntervalListener extends LifecycleOwner {
void onTimerInterval();
}
private final Handler mHandler = new Handler(Looper.getMainLooper());
private final long mInterval;
private final OnIntervalListener mOnIntervalListener;
public LifecycleAwareTimer(long interval, @NonNull OnIntervalListener onIntervalListener) {
mInterval = interval;
mOnIntervalListener = onIntervalListener;
mOnIntervalListener.getLifecycle().addObserver(this);
}
@Override
public void run() {
mOnIntervalListener.onTimerInterval();
}
@Override
public void onResume(@NonNull LifecycleOwner owner) {
mHandler.removeCallbacksAndMessages(null);
mHandler.postDelayed(this, mInterval);
}
@Override
public void onPause(@NonNull LifecycleOwner owner) {
mHandler.removeCallbacksAndMessages(null);
}
@Override
public void onDestroy(@NonNull LifecycleOwner owner) {
mHandler.removeCallbacksAndMessages(null);
mOnIntervalListener.getLifecycle().removeObserver(this);
}
}
Now, you can use it creates a new instance from Activity or Fragment and it will die once its owner dies.