【问题标题】:Need help trying to figure out Android intent constructor需要帮助试图找出 Android 意图构造函数
【发布时间】:2015-09-04 16:38:22
【问题描述】:

我正在尝试学习如何开发 Android 应用程序。我正在阅读 Android 开发人员指南网站 http://developer.android.com/guide/components/intents-filters.html,特别是关于 Explicit 与 Implicit Intents 的内容。显式意图的示例之一如下所示:

// Executed in an Activity, so 'this' is the Context
// The fileUrl is a string URL, such as "http://www.example.com/image.png"
Intent downloadIntent = new Intent(this, DownloadService.class);
downloadIntent.setData(Uri.parse(fileUrl));
startService(downloadIntent);

构造函数 Intent(this, DownloadService.class) 看起来像 Android API 中的这个公共构造函数 (http://developer.android.com/reference/android/content/Intent.html):

public  Intent (Context packageContext, Class<?> cls) 

Intent 构造函数文档指出:

为特定组件创建意图。所有其他字段(操作、数据、类型、类)都是空的,尽管稍后可以通过显式调用对其进行修改。这提供了一种方便的方法来创建旨在执行硬编码类名的意图,而不是依赖系统为您找到合适的类;请参阅 setComponent(ComponentName) 了解有关此影响的更多信息。

我想弄清楚的是,构造函数中的“this”是什么?我的意思是,我知道一般的“this”是什么(您的活动的当前实例),但是在这个特定的内容中它是什么?在 cmets 中,它说“在 Activity 中执行,所以 'this' 是上下文”,但“上下文”是什么?它不是构成意图的五种信息之一(组件名称、操作、数据、类别、附加信息、标志)。我知道“Do​​wnloadService.class”参数是组件名称,所以我只是想弄清楚它是什么。

【问题讨论】:

  • 好吧Activity 扩展了Context。来自文档It allows access to application-specific resources and classes, as well as up-calls for application-level operations such as launching activities, broadcasting and receiving intents, etc.

标签: android


【解决方案1】:

我想弄清楚的是,构造函数中的“this”是什么?

它是Context 的某个子类的实例,例如Activity

它不是构成意图的五种信息之一(组件名称、操作、数据、类别、附加信息、标志)。

不,但是Context 和Java 类的组合足以构建ComponentNameComponentName 是应用程序 ID 和该应用程序中组件的完全限定类名的组合。 Java 类可以提供完全限定的类名; ContextComponentName 提取应用程序 ID 的位置(在这种情况下,用于您自己的应用程序)。

【讨论】:

  • 那么为什么需要它呢?根据 Android 开发者指南,创建 Intent 只需要这 5 条信息。
  • @Brian:“那为什么需要它呢?” -- 正如我所写,您正在使用Context 和Java 类的组合来构建ComponentNameComponentName 是使 Intent 明确的原因。 “我知道“Do​​wnloadService.class”参数是组件名称”——不,不是。实现组件的是Java类,但不是Intent使用的ComponentNameJava对象。
  • 啊...好吧,我想我现在明白了。因此,当文档说“Intent 的这个字段是一个 ComponentName 对象,您可以使用目标组件的完全限定类名来指定它,包括应用程序的包名。”,而不是写“com.example. ExampleActivity” 我可以写“this, ExampleActivity.class”?
  • @Brian:嗯,不完全是。字段是一个字段,它包含一个 Java 对象。您引用的字段包含ComponentName,而不是String。在幕后,您正在讨论的Intent 构造函数从Context 和Java 类中为您创建了ComponentName。欢迎您通过其他方式在Intent 中填充ComponentName
  • 知道了...谢谢。作为一个附带问题,您的书是实体版还是数字版?之前看到推荐过,一直在考虑入手。
猜你喜欢
  • 1970-01-01
  • 2010-12-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多