I'd like to get the name of the current Activity
to be sent along in the URI of an HttpRequest
. Is there a way to do this without referring specifically to the Activity
?
I know I can do myActivity.class.toString()
but this is just a less efficient way of hard coding "myActivity" since I'm making a static reference to my Activity
. Is there a more general way to do this using something like 'this' (which btw doesn't actually work here because it returns more information than what's desired).
Use this. getClass(). getSimpleName() to get the name of the Activity.
Intent intent = getIntent(); String activity = intent. getStringExtra("activity"); Now in the string activity you will get the name from which Activity it has came.
This example demonstrates How to get current activity name in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.
Use this.getClass().getSimpleName()
to get the name of the Activity.
From the comments, if you're in the context of an OnClickListener
(or other inner class), specify the class manually:
MainActivity.class.getSimpleName()
For purists out there who may not want to use reflection, an alternative way is to use the PackageManager
as follows:
PackageManager packageManager = activity.getPackageManager(); try { ActivityInfo info = packageManager.getActivityInfo(activity.getComponentName(), 0); Log.e("app", "Activity name:" + info.name); } catch (NameNotFoundException e) { e.printStackTrace(); }
However this seems like a lot of work just to do the same as getClass().getName()
(and not even getSimpleName()
). But I guess it may be useful for someone who wants more information about the activity than just the class name.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With