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