android学习—— context 和 getApplicationContext()


本文解决了dialog使用全局context报错的原因:对话框使用的是activity的context。不是全局的

这个谷歌官方的博客写到,主要是为了帮助解决内存泄漏,的博客文章,同时也给contexts提供了一些良好的信息:

In a regular Android application, you usually have two kinds of Context, Activity and Application.
在一个普通的Android应用程序中,你通常有两种Context,Activity和Application。

Reading the article a little bit further tells about the difference between to the two and why you might want to consider using the application Context (Activity.getApplicaitonContext()) rather than using the Activity context ("this"). Basically the Application context is associated with the Applicaiton and will always be the same throughout the life cycle of you app, where as the Activity context is associated with the activity and could possible be destroyed many times as the activity is destroyed during screen orientation changes and such.
如果再深入读下这篇文章,它告诉了我们这两种Context的不同,并且为什么你会考虑使用应用程序Context(Activity.getApplicaitonContext())而不是使用活动Context(即"this")。基本上来说呢,应用程序Context是和应用程序关联的,并且在程序的生命周期内,总是一样的。但是,活动Context是关联在某个活动上的,随着Activity的销毁(比如横竖屏切换等情况),这个Context也会被销毁N多次。

So overall it seems preferable to use the global application context when possible.
所以,总体来说,似乎最好在可能的情况下使用全局应用程序Context。

I got bad window token errors when using application context to Progress Dialog. So i used activity context instead. 
我使用应用程序Context给进度条对话框的时候,出现了“window token errors”的错误。所以,我使用了活动Context,而不是应用程序Context。

在android中常常会遇到与context有关的内容

http://mycoding.iteye.com/blog/1944779

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

new AlertDialog.Builder(getApplicationContext())时发生错误:

E/AndroidRuntime(5844): android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application

于是查了查:

getApplicationContext() 生命周期是整个应用,应用摧毁它才摧毁 Activity.this的context属于activity ,activity 摧毁他就摧毁

activity.this要返回一个activity,而getApplicationContext()就不一定返回一个activity

 

 

getApplicationContext() 返回应用的上下文,生命周期是整个应用,应用摧毁它才摧毁
Activity.this的context 返回当前activity的上下文,属于activity ,activity 摧毁他就摧毁

getBaseContext()  返回由构造函数指定或setBaseContext()设置的上下文

 

http://blog.csdn.net/janronehoo/article/details/7348566



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值