Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Activity name dynamically - android

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).

like image 753
evanmcdonnal Avatar asked May 16 '12 23:05

evanmcdonnal


People also ask

How to get Activity name in Android programmatically?

Use this. getClass(). getSimpleName() to get the name of the Activity.

How can I get previous activity name in Android?

Intent intent = getIntent(); String activity = intent. getStringExtra("activity"); Now in the string activity you will get the name from which Activity it has came.

How can I get current activity?

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.


2 Answers

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()

like image 145
Kevin Coppock Avatar answered Sep 23 '22 17:09

Kevin Coppock


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.

like image 28
darrenp Avatar answered Sep 21 '22 17:09

darrenp