Get Activity name dynamically - android
ActivityManager am = (ActivityManager)context.getSystemService(ACTIVITY_SERVICE);
List< ActivityManager.RunningTaskInfo > taskInfo = am.getRunningTasks(1);
this.currentActivity = taskInfo.get(0).topActivity.getClassName();
Log.i( "CURRENT Activity ", currentActivity);
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.
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()