13

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

Thanks a lot!

0

5 Answers 5

23

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(); 
Sign up to request clarification or add additional context in comments.

2 Comments

The application's className would just output some garbage like com.android.tools.fd.runtime.BootstrapApplication
launchIntent.getComponent() could return null, because not all lauchend intents contains the respective component. developer.android.com/reference/android/content/…
18

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

Comments

1

This worked perfectly for me in Kotlin:

callingActivity::class.simpleName 

or in Java:

activity.getClass().getSimpleName() 

Comments

0

How to get the Activity class name in Kotlin:

val packageName = context.packageName val launchIntent = context.packageManager.getLaunchIntentForPackage(packageName) val className = launchIntent?.component?.className ?: return null 

How to get the Activity class from the class name in Kotlin:

return try { Class.forName(className) } catch (e: ClassNotFoundException) { e.printStackTrace() null } 

Comments

-2

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.