Home » Android » android – How to get main Activity class or class name of my application?

android – How to get main Activity class or class name of my application?

Posted by: admin May 14, 2020 Leave a comment

Questions:

How to get main Activity class or class name of my application?

Thanks a lot!

How to&Answers:

To get your launcher activity use http://developer.android.com/reference/android/content/pm/PackageManager.html#getLaunchIntentForPackage(java.lang.String)

getLaunchIntentForPackage

On this Intent call getComponentName and from the returned CompomemtName call getClassName

http://developer.android.com/reference/android/content/ComponentName.html

Answer:

Thanks to Lee for explaining how to get the classname, here’s the code:

String packageName = context.getPackageName();
Intent launchIntent = context.getPackageManager().getLaunchIntentForPackage(packageName);
String className = launchIntent.getComponent().getClassName();

Answer:

I just set a variable in my main activity like so… public static Activity activity = this; then I can reference it from anywhere using: MainActivity.activity.

You can also set it in the onCreate() method, just set up the variable at the top of your main activity class like this public static Activity activity; then in the onCreate() method just add activity = this; anywhere.

This will work for any class that extends Activity, for example public class MainActivity extends Activity however you can call the variable from any class even if they don’t extend Activity.

Hope this helps.