Run an action in the main application from the Android library module

I am creating my first library module, which I plan to populate with reusable code for several projects. My first roadblock is that I need to be able to start activity in the main application from the library module.

For example, I have a splash screen activity. It works for 2 seconds, then starts the main action. I believe that I can reuse this splash screen activity, and I want to put it in my library module. However, I am not sure how to start the main activity from the library.

Mainfest in the main application 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 is currently in my library module.

Since the library is a dependency of the main application, and not vice versa, I'm not sure how to start MainActivity from my SplashScreenActivity . It's not so easy:

 Intent i = new intent(this, MainActivity.class); startActivity(i); 
+5
source share
2 answers

I remove SplashScreenActivity from the main manifest and create a protected method called startMainActivity() or similar. Call this method in your base class SplashScreenActivity in the place you would normally like to run MainActivity .

Then inside your main project I would subclass SplashScreenActivity and override the startMainActivity() method to execute the behavior you want. Remember to place your subclass of SplashScreenActivity inside your main project manifest.

This way you can easily use the SplashScreenActivity behavior in all of your projects, which may depend on it.

+2
source

You should not do that. You strongly bind these two classes (the class that launches activity from lib and Activity to load.

Instead, you can configure broadcast reception in the application, which will receive the intent object and begin the action for you. If in the future you want other actions or services to be started remotely, you can use the same broadcast receiver to receive requests from your library. all you have to do is add data to the Intent Extras collection, which will contain what activity to open (or any other task, of course).

This solution cancels the sharing of your lib and application, it is better wize architecture (in my opinion).

Good luck

0
source

Source: https://habr.com/ru/post/1240953/


All Articles