Android app lifecycle engine library

373 views Asked by At

For a project, I need something like a generic flexible lifecycle engine. What I mean is, I should be able to register a number of components with it. The components should be triggered on different app/activity lifecycle events.

For example:

  • component A reacts to onStart(), onStop() and onDestroy()
  • component B reacts to onStart() and onPause()

In addition components should be able to react to other components/events.

For example:

  • component C gets triggered when components A and B have finished a specific task

Before I start to write something myself, I wanted to check if there is already a library out there that can do such things.

1

There are 1 answers

2
Piotr Wittchen On

You can create your custom Application class extending Android Application class. Next, you can create and register ActivityLifecycleCallbacks. After that, you can implement your logic inside the callbacks.

public class MyApplication extends Application {

   @Override
   public void onCreate () {
      super.onCreate();
      registerActivityLifecycleCallbacks(new MyActivityLifecycleCallbacks());
   }

   private static final class MyActivityLifecycleCallbacks implements ActivityLifecycleCallbacks {

      public void onActivityCreated(Activity activity, Bundle bundle) {
         Log.e("","onActivityCreated:" + activity.getLocalClassName());
      }

      public void onActivityDestroyed(Activity activity) {
         Log.e("","onActivityDestroyed:" + activity.getLocalClassName());
      }

      public void onActivityPaused(Activity activity) {
         Log.e("","onActivityPaused:" + activity.getLocalClassName());
      }

      public void onActivityResumed(Activity activity) {
         Log.e("","onActivityResumed:" + activity.getLocalClassName());
      }

      public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
         Log.e("","onActivitySaveInstanceState:" + activity.getLocalClassName());
      }

      public void onActivityStarted(Activity activity) {
         Log.e("","onActivityStarted:" + activity.getLocalClassName());
      }

      public void onActivityStopped(Activity activity) {
         Log.e("","onActivityStopped:" + activity.getLocalClassName());
      }
   }
}