何时在Android中为ComponentName使用哪个构造函数? [英] When to use which constructor for ComponentName in Android?
问题描述
我对Android中的ComponentName类有点困惑。
I am a little bit confused about the ComponentName class in Android.
有多种方法可以获取组件名称对象,但是我不知道何时使用哪个...以及为什么!
There are different ways to get to a component name object, but I don't know when to use which... and why!
示例:
- 应用程序包是
de.zordid.sampleapp
- ,但窗口小部件提供程序类是
de.zordid.sampleapp.widget.WidgetProvider
- Application package is
de.zordid.sampleapp
- but widget provider class is
de.zordid.sampleapp.widget.WidgetProvider
使用
ComponentName cn = new ComponentName("de.zordid.sampleapp.widget",
"WidgetProvider");
我得到了以下组件信息: ComponentInfo {de.zordid.sampleapp.widget / WidgetProvider}
,但我无法使用它-组件未知!
但是JavaDoc说我应该给程序包和该程序包中的类-这就是我所做的,不是吗?
I got this component info: ComponentInfo{de.zordid.sampleapp.widget/WidgetProvider}
, but I could not use this - the component is unknown!
But the JavaDoc says I should give the package and the class within that package - and that is what I did, didn't I??
使用
ComponentName cn = new ComponentName(context, WidgetProvider.class);
收益 ComponentInfo {de.zordid.sampleapp / de.zordid.sampleapp。 widget.WidgetProvider}
-很好!!
甚至还有另一种获取ComponentName的方法-通过上下文和字符串。
应该在何时何地使用哪个??
There is even another way to get a ComponentName - by context and a string. Which one should be used where and when??
谢谢!
推荐答案
带有两个 String
的 ComponentName
构造函数可用于引用另一个应用程序中的组件。但是,第一个参数不是类的包名称;它是应用程序的程序包名称--该应用程序<$ c中清单
元素的 package
属性$ c> AndroidManifest.xml 。因此,第一个示例应该是
The ComponentName
constructor taking two String
s can be used to refer to a component in another application. But, the first argument is not the package name of the class; it is the package name of the application---the package
attribute of the manifest
element in that application's AndroidManifest.xml
. So your first example should be
ComponentName cn = new ComponentName("de.zordid.sampleapp",
"de.zordid.sampleapp.widget.WidgetProvider");
该构造函数当然可以用于引用您自己的应用程序中的组件,但是由于您已经拥有您自己的应用程序中的 Context
,您不妨使用它并使用其他构造函数之一。我认为,使用 Class
的人应该是首选。如果由于某种原因仅动态知道该类,则可以使用带有 String
的那个。在这种情况下,应使用上述完全限定的类名称。
That constructor could certainly be used to refer to components in your own application, but since you already have hold of a Context
from your own application you might as well use it and use one of the other constructors. In my opinion, the one taking a Class
should be preferred whenever usable. You could use the one taking a String
if you only know the class dynamically for some reason; in that case, it should take the fully-qualified class name as above.
这篇关于何时在Android中为ComponentName使用哪个构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!