🤖
Android Tips
  • 🤖AOSP
    • Clone AOSP repository
    • Directory Structure
    • Setup IDE
      • Setup VSCode
    • Build
      • BluePrint for Application Project
      • BluePrint for Android Library Project
    • Manifest
      • sharedUserId
      • persistant
  • Gradle
    • Create Custom Build Config Variables
    • Create Custom manifest Variables
    • Make app debugable
  • Android Process
    • Find a process by name
    • Kill a process by Id
  • Catch any exception in Android
  • 🎨Theming
    • Theming
      • RRO
        • RRO Internals
        • RRO classes in AOSP
        • RRO Example
        • RRO Permission
      • Fabricated RRO (FRRO)
        • FRRO Example
        • Permission
  • Lifecycle
    • Basics
      • Lifecycle
        • Activity
        • Fragment
          • Fragment add
    • Lifecycle Aware Custom Class
  • â„šī¸Interview
    • Interview Questions
    • Architecture Pattern
      • MVC Architecture pattern
      • MVP Architecture Pattern
      • MVVM Architecture Pattern
  • â†”ī¸AIDL
    • Simple AIDL Communication
      • Creating an AIDL file
      • Create an AIDL server
      • Create AIDL client
      • Limitations
    • AIDL with callback
      • Create AILD interfaces
      • Create an AIDL server
      • Create AIDL client
Powered by GitBook
On this page
  1. Lifecycle

Lifecycle Aware Custom Class

A custom business class that can be lifecycle aware, just like ViewModel

PreviousFragment addNextInterview Questions

Last updated 1 year ago

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 .

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