动态获取活动名称-android

我想得到当前 Activity的名称沿着 HttpRequest的 URI 发送。有没有一种方法可以做到这一点,而不具体提到 Activity

我知道我可以做 myActivity.class.toString(),但这只是一个硬编码“ myActivity”的效率较低的方法,因为我正在对我的 Activity进行静态引用。有没有一种更通用的方法来实现这一点,比如使用“ this”(顺便说一下,它在这里实际上不起作用,因为它返回的信息超出了预期)。

110308 次浏览

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.

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

First: open your manifest.xml file

you will find your package name i.e. "com.company.projectname"

Then: lets say your activity name is MainActivity

MainActivity.class.getCanonicalName() >output> "com.company.projectname.MainActivity"

OR

MainActivity.class.getSimpleName() >output> "MainActivity"

OR

MainActivity.class.getName() >output> "com.company.projectname.MainActivity"

For Xamarin

string GetActivityClassName(Activity activity) //Receiving LoginActivity
{
//ComponentName
activity.ComponentName; //Output: "md5101a0260d0a0e5d40a0a9009be09b0c2.LoginActivity"


//LocalClassName
activity.LocalClassName; //Output: "md5101a0260d0a0e5d40a0a9009be09b0c2.LoginActivity"


//Java.Lang.Class.FromType.SimpleName
Java.Lang.Class.FromType(activity.GetType()).SimpleName; //Output "LoginActivity"


//Type.Name
activity.GetType().Name; //Output "LoginActivity"
}