1

I'm still fairly new to the programming world in general, so I hope this isn't an obvious/abstract question.

I'm developing an android library that needs to monitor the lifecycle events of the activity that's using it. How do I accomplish this while creating the least amount of work for the developer using my library? Preferably, I like to use something that is already built into Android.

I've seen similar questions, such as: Automatically log Android lifecycle events using ActivityLifecycleCallbacks? But it doesn't really apply to a library project.

Am I missing something? Any insight would be greatly appreciated.

Community
  • 1
  • 1
deMouser
  • 369
  • 1
  • 2
  • 14

1 Answers1

1

I think that your best (long term) option is to have a setup along with the integration of the library (i.e. pass the Application in an entry point of your library).

That said, there is an undocumented way to get the current Application. as described here: https://stackoverflow.com/a/12495865/458365

try {
    final Class<?> activityThreadClass =
        Class.forName("android.app.ActivityThread");
    final Method method = 
    activityThreadClass.getMethod("currentApplication");
    return (Application) method.invoke(null, (Object[]) null);
} catch (final Exception e) {
    // handle exception
}

Once you have that you can call Application.registerActivityLifecycleCallbacks() to register your own ActivityLifecycleCallbacks

Update: Another alternative to get the application (Context) that I've come across is to use a Content provider. I think libraries like Firebase use this method because it has zero set up. However, it requires the consumer of the library to have an application object (which actually is the same as with the manual method) but it does look a lot cleaner:

Inside the onCreate of the CP we can cast getContext as Application and go from there with the Callbacks process.

Source: https://medium.com/@andretietz/auto-initialize-your-android-library-2349daf06920

Community
  • 1
  • 1
pablisco
  • 14,027
  • 4
  • 48
  • 70