Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling an Application Activity from a Library Project in Android

Ok,

So I'm making a library project of UI elements. The Library has some activities which are based of ActionBarSherlock which is a backwards compatibility library for the action bar in android. In these activities I would like to have a button in the action bar which will take the user home regardless of which activity they are using in the Library project.

Some terminology. The 'library' refers to the Android UI library project I'm working on. The 'Application' refers to whatever customer a developer might be using with the Library included.

Usually, when you make an activity and you want to call another, you would do something like this.

intent = new Intent(this, WhateverMyActivityName.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);

Simple enough. But here's the tricky bit. Android Libraries have little to no knowledge of what application is using them. So 'WhateverMyActivityName.class' is useless as there is no way to predict what the developers application will call their activities.

I need to replace

intent = new Intent(this, WhateverMyActivityName.class);

with something like this

intent = new Intent(this, getApplication().MainActivity().getClass());

or possibly use some sort of intent action which will call the main Activity in the application (Intent.ACTION_MAIN or Intent.CATEGORY_LAUNCHER)

So in short: How do I get an applications main activity from a library project?

like image 517
OVERTONE Avatar asked Dec 11 '22 22:12

OVERTONE


2 Answers

We can use reflection to get class object.

Class.forName("com.mypackage.myMainActivity")

Add this code in Library project to call,

try {
      Intent myIntent = new Intent(this,Class.forName("com.mypackage.myMainActivity"));
      startActivity(myIntent );
} catch (ClassNotFoundException e) {
     e.printStackTrace();
}

"com.mypackage.myMainActivity" is the Activity present in Main project, that we need to call from its Library project.

like image 199
Ganapathy C Avatar answered Dec 28 '22 08:12

Ganapathy C


The application calls some method in your library providing the Intent to be invoked, or providing the Class of the activity to be invoked. Your library stores that someplace and uses it.

Your assumption that the right answer is "Intent.ACTION_MAIN or Intent.CATEGORY_LAUNCHER" may be inaccurate. For example, some apps have that be a splash screen activity (which is an issue in its own right, but that's beside the point), and that would not be where a home affordance within the app should go.

like image 45
CommonsWare Avatar answered Dec 28 '22 08:12

CommonsWare