How to get main Activity class or class name of my application?
Thanks a lot!
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(); 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
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 } 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.