Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to start main activity from a library?

I am using a Project A, and a library project to develop my Android app. Both of these projects have activities in them. If I am currently in Project A, then it is easy to just start an activity in the library project by just importing it. However, I'm not sure how to start an Activity in Project A if I am coming from an activity in the library project. I'm trying to make the library project independent of the package name of the Project A since I will be using it for multiple apps. Any ideas on how to do this? Thanks.

like image 765
user1132897 Avatar asked Feb 20 '23 10:02

user1132897


2 Answers

There are a few possible solutions.

The best is to register an intent filter in the Manifest entries for the activities that you wish to be accessible to your other projects. There is a great tutorial on intent filters here.

Another option would be to pass a Class to the library project, and use the Intent (Context packageContext, Class cls) constructor to create an intent to fire off and start the activity. It would be a better practice and learning experience to use intent filters, however.

Good luck!

like image 159
Zambotron Avatar answered Feb 22 '23 01:02

Zambotron


I believe this is to be the simplest answer: you'll need an object which exists in the library, which you can extend in your project.

Imagine that your library has a LibraryApplication which your ProjectApplication extends. The LibraryActivity can call:

((LibraryApplication)getApplication()).startNewActivity(this, "goHome")

Your ProjectApplication implements this new method:

public void startNewActivity(Context context, String action) {
    if("goHome".equals(action)) {
        startActivity(context, ProjectHomeActivity.class);
    }
}
like image 26
FunkTheMonk Avatar answered Feb 22 '23 00:02

FunkTheMonk