Unfortunately, it's not possible to have multiple Application
classes, but there are workarounds, depending on what you're trying to do.
An Android application can only have a single Application
subclass that's used as the application context.
This is because every Context
in the app has a reference to it that can be retrieved by getApplicationContext()
. There's no provision for multiple application contexts, and no way to specify whether you want the "library application context" or the "main application context."
Assuming that what you want to do is initialize your library on app startup, you can simply create an empty ContentProvider
that's android:exported="false"
and do your initialization in its onCreate
method. This will be called before the app's Application.onCreate
.
<provider
android:name="com.my.library.MyLibraryInitializer"
android:authorities="${applicationId}.mylibrary-initializer"
android:exported="false"/>
public class MyLibraryInitializer extends ContentProvider {
@Override
public boolean onCreate() {
// perform your initialization here
return true;
}
// Everything below here is just boilerplate to implement the abstract methods
// in ContentProvider, no need to change it
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
return null;
}
@Override
public Uri insert(Uri uri, ContentValues values) {
return null;
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
return 0;
}
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
return 0;
}
@Override
public String getType(Uri uri) {
return null;
}
}
This is, for example, what WorkManager does to initialize itself: it declares a provider in its manifest and performs its initialization within the onCreate
method of that ContentProvider
.