# Lifecycle Aware Custom Class

Here is an example of timer, it can start and pause and destroy based on current lifecycle of attached Activity, Fragment or even an lifecycle aware [service](https://developer.android.com/reference/androidx/lifecycle/LifecycleService#).

```java
/**
 * @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);
    }
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://notes.tejpratapsingh.com/android-tips/lifecycle/lifecycle-aware-custom-class.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
