来自developer.android.com的课程
public void sendMessage(View view) {
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
Context作为它的第一个参数(因为Activity类是Context的子类,所以使用它)
=============
为什么你需要这个'?
答案 0 :(得分:-1)
public Intent(Context packageContext,Class cls)
参数
packageContext实现此目的的应用程序包的上下文 类。
cls用于意图的组件类。
正如你所说的那样
java.lang.Object
↳ android.content.Context //see this
↳ android.content.ContextWrapper
↳ android.view.ContextThemeWrapper
↳ android.app.Activity // see this
您的课程扩展了活动。
public class YouActivity extends Activity // extends Activity
因此this
引用活动上下文,第一个意图参数是相同的。
检查此链接
但是我会尝试更好地解释。
查看源代码
3811
3812 public Intent(Context packageContext, Class<?> cls) {
3813 mComponent = new ComponentName(packageContext, cls);
3814 }
然后
61
62 public ComponentName(Context pkg, String cls) {
63 if (cls == null) throw new NullPointerException("class name is null");
64 mPackage = pkg.getPackageName(); // see this
65 mClass = cls;
66 }
而getPackageName()
是Context
的方法。
public abstract String getPackageName ()
Added in API level 1
Return the name of this application's package.
注意
Intent intent = new Intent(this, DisplayMessageActivity.class);
这是明确的意图。您通常会使用显式意图在您自己的应用中启动组件,因为您知道要启动的活动或服务的类名。
我包括Chris Stratton的评论,因为他更好地解释了为什么你需要一个上下文作为第一个参数。
有一些方法可以创建一个不需要Context的Intent。 但是,如果您想要定位特定包的特定类,那么 为目标包提供上下文是一种可行的方法。 请注意,上面的代码利用了目标类的事实 在与发件人相同的包中,所以发件人(“this”)在减少时 一个包上下文也将是适当的包上下文 目标。情况并非总是如此。
进一步阅读明确和隐含的Intetns @
http://developer.android.com/guide/components/intents-filters.html
并检查
http://developer.android.com/training/basics/intents/sending.html