Android Context几种获取方法区别

在Android开发中常常遇到Context(上下文)这个参数,调用很多函数的时候经常要传递这个参数过去.而默认Android中有好几个函数返回值是Context变量,而这些函数也不知道原理是啥.所以Google搜了一下在stackoverflow上看到有人回答,就顺便贴过来,备忘吧.


getApplicationContext() Application context is associated with the Application and will always be the same throughout the life cycle.
这个函数返回的这个Application的上下文,所以是与app挂钩的,所以在整个生命周期里面都是不变的

getBasecontext() should not be used just use Context instead of it which is associated with the activity and could possible be destroyed when the activity is destroyed.
stackoverflow上面写的是,这个函数不应该被使用,用Context代替,而Context是与activity相关连,所以当activity死亡后可能会被destroyed

getApplication() is available to Activity and Services only. Although in current Android Activity and Service implementations, getApplication() and getApplicationContext() return the same object, there is no guarantee that this will always be the case (for example, in a specific vendor implementation). So if you want the Application class you registered in the Manifest, you should never call getApplicationContext() and cast it to your application, because it may not be the application instance (which you obviously experienced with the test framework).
getApplication只能被Activity和Services使用,虽然在现在的android的实现中,getApplication和getApplicationContext返回一样的对象,但也不能保证这两个函数一样(例如在特殊的提供者来说),所以如果你想得到你在Manifest文件里面注册的App class,你不要去调用getApplicationContext,以为你可能得不到你所要的app实例(你显然有测试框架的经验)。。。。

getParent() returns object of the activity if the current view is a child..In other words returns the activity object hosting the child view when called within the child.
返回activity的上下文,如果这个子视图的话,换句话说,就是当在子视图里面调用的话就返回一个带有子视图的activity对象

在语句 AlertDialog.Builder builder = new AlertDialog.Builder(this); 中,要求传递的 参数就是一个context,在这里我们传入的是this,那么这个this究竟指的是什么东东呢? 这里的this指的是Activity.this,是这个语句所在的Activity的this,是这个Activity 的上下文。网上有很多朋友在这里传入getApplicationContext(),这是不对的。 AlertDialog对象是依赖于一个View的,而View是和一个Activity对应的。 于是,这里涉及到一个生命周期的问题,this.getApplicationContext()取的是这个应 用程序的Context,Activity.this取的是这个Activity的Context,这两者的生命周期是不同 的,前者的生命周期是整个应用,后者的生命周期只是它所在的Activity。而AlertDialog应 该是属于一个Activity的,在Activity销毁的时候它也就销毁了,不会再存在;但是,如果传 入getApplicationContext(),就表示它的生命周期是整个应用程序,这显然超过了它 的生命周期了。 所以,在这里我们只能使用Activity的this。

在找以上四个区别的时候又发现360DOC上面的Context的介绍文
Android上的Context

不过查一遍我还是没找到区别,我可能还是不知道区别在哪里....
update:2013/12/24
今天重新回顾一下,貌似有点明白了,和生命周期有关系,Context上下文,依赖关系。

Related Articles

0 评论 :

发表评论

Quote Of The Day