Search code examples
androidandroid-library

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.


Solution

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