h_k
h_k

Reputation: 1714

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);

Upvotes: 6

Views: 3023

Answers (2)

FunkSoulBrother
FunkSoulBrother

Reputation: 2157

You shouldn't do it that way. You are strongly coupling these two classes (the class starting the activity from the lib and the Activity to be loaded.

Instead - you can set up a broadcast receive in the app which will receive an intent object and start the activity for you. If, in the future, you'll want other activities or services to be started remotely - you'll be able to use the same broadcast receiver to accept requests from your lib. all you have to do is add data to the Intent's Extras collection that will contain which Activity to open (or any other task of course).

This solution de-couples your lib and app, it's better architecture wize (in my opinion).

Good luck!

Upvotes: 2

Mateusz Herych
Mateusz Herych

Reputation: 1605

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.

Upvotes: 2

Related Questions