Search code examples
androidandroid-library

Launch an activity in main app from an Android Library Module


I am building my first library module that I am planning on filling with reusable code for multiple projects. My first roadblock is that I need to be able to launch an activity in the main app from the library module.

For example, I have a splash screen activity. It runs for 2 seconds, then launches the main activity. I believe that I can reuse this splash screen activity, and I want to put it in my library module. However, I am unsure how to launch the main activity from the library.

Mainfest in main app setup:

<activity
    android:name="com.example.myLibraryModule.SplashScreen"
    android:theme="@style/AppTheme.NoActionBar">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

The manifest launches the splash screen which currently resides in my library module.

Since the library is a dependency of the main application and not the other way around, I am not sure how to go about launching the MainActivity from my SplashScreenActivity. It's not as easy as:

Intent i = new intent(this, MainActivity.class);
startActivity(i);

Solution

  • I'd remove SplashScreenActivity from your main manifest and create a protected method called startMainActivity() or alike. Call this method within your SplashScreenActivity base class at a place you normally would like to start your MainActivity.

    Then inside of your main project I would subclass SplashScreenActivity and override the startMainActivity() method to perform a behavior you wish. Don't forget to put your SplashScreenActivity subclass inside of your main project's manifest.

    This way you can reuse SplashScreenActivity's behavior easily in all your projects that may depend on it.