Android 如何获取我的应用程序的主要活动类或类名?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10573930/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 04:12:37  来源:igfitidea点击:

How to get main Activity class or class name of my application?

android

提问by IgorOK

How to get main Activity class or class name of my application?

如何获取我的应用程序的主要活动类或类名?

Thanks a lot!

非常感谢!

回答by sroes

Thanks to Lee for explaining how to get the classname, here's the code:

感谢 Lee 解释如何获取类名,代码如下:

String packageName = context.getPackageName();
Intent launchIntent = context.getPackageManager().getLaunchIntentForPackage(packageName);
String className = launchIntent.getComponent().getClassName();

回答by Lee

To get your launcher activity use http://developer.android.com/reference/android/content/pm/PackageManager.html#getLaunchIntentForPackage(java.lang.String)

要获取您的启动器活动,请使用http://developer.android.com/reference/android/content/pm/PackageManager.html#getLaunchIntentForPackage(java.lang.String)

getLaunchIntentForPackage

On this Intent call getComponentNameand from the returned CompomemtName call getClassName

在此 Intent 调用getComponentName和返回的 CompomemtName 调用中getClassName

http://developer.android.com/reference/android/content/ComponentName.html

http://developer.android.com/reference/android/content/ComponentName.html

回答by Luke Alderton

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.

我只是在我的主要活动中设置一个变量,就像这样......public static Activity activity = this;然后我可以从任何地方使用: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.

您也可以在 onCreate() 方法中设置它,只需像这样public static Activity activity;在主活动类的顶部设置变量,然后在 onCreate() 方法中添加activity = this;任何地方即可。

This will work for any class that extends Activity, for example public class MainActivity extends Activityhowever you can call the variable from any class even if they don't extend Activity.

例如,这适用于扩展 Activity 的任何类,public class MainActivity extends Activity但是您可以从任何类调用变量,即使它们不扩展 Activity。

Hope this helps.

希望这可以帮助。