它来自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);}
上下文作为其第一个参数(之所以使用,是因为Activity类是Context的子类)
=============
为什么需要“这个”?
解决方法:
public Intent (Context packageContext, Class cls)
Parameters
packageContext A Context of the application package implementing this
class.cls The component class that is to be used for the intent.
就像你说的对
java.lang.Object ↳ androID.content.Context //see this ↳ androID.content.Contextwrapper ↳ androID.vIEw.ContextthemeWrapper ↳ androID.app.Activity // see this
您的课程扩展了Activity.
public class YouActivity extends Activity // extends Activity
因此,这指的是活动上下文,意图的第一个参数是相同的.
检查此链接
http://startandroid.ru/en/lessons/complete-list/229-lesson-22-intent-intent-filter-context-theory.html
但是我会尽力解释得更好.
看一个源代码
38113812 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 this65 mClass = cls; 66 }
getPackagename()是Context的方法.
public abstract String getPackagename ()Added in API level 1Return the name of this application's package.
注意
Intent intent = new Intent(this, displayMessageActivity.class);
这是明确的意图.通常,您将使用明确的意图在自己的应用程序中启动组件,因为您知道要启动的活动或服务的类名.
我包括克里斯·斯特拉顿(Chris Stratton)的评论,因为他更好地解释了为什么需要上下文作为第一个参数.
There are ways of creating an Intent which do not require a Context.
But if you want to target a specific class of a specific package, then
provIDing a context for the target package is a ready way to do that.
Note that the above code Leverages the fact that the target class is
in the same package as the sender, so the sender (“this”) when reduced
to a package context will also be the proper package context for the
target. That won’t always be the case.
进一步阅读@显式和隐式解释@
http://developer.android.com/guide/components/intents-filters.html
还要检查
http://developer.android.com/training/basics/intents/sending.html
总结以上是内存溢出为你收集整理的为什么必须在Android开发中将此Context作为参数传递?全部内容,希望文章能够帮你解决为什么必须在Android开发中将此Context作为参数传递?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)