android学习—— context 和 getApplicationContext()
来源:互联网 发布:vb中最基本的对象是 编辑:程序博客网 时间:2024/06/05 18:18
在android中常常会遇到与context有关的内容
浅论一下context :
在语句 AlertDialog.Builder builder = new AlertDialog.Builder(this); 中,要求传递的 参数就是一个context,在这里我们传入的是this,那么这个this究竟指的是什么东东呢?
这里的this指的是Activity.this,是这个语句所在的Activity的this,是这个Activity 的上下文 context。
网上有很多朋友在这里传入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()
- android学习—— context 和 getApplicationContext()
- android学习—— context 和 getApplicationContext()
- android学习—— context 和 getApplicationContext()
- android学习—— context 和 getApplicationContext()
- android学习—— context 和 getApplicationContext()
- android学习—— context 和 getApplicationContext()
- android学习—— context 和 getApplicationContext()
- android学习—— context 和 getApplicationContext()
- android学习—— context 和 getApplicationContext()
- android学习—— context 和 getApplicationContext()
- android学习—— context 和 getApplicationContext()
- android学习—— context 和 getApplicationContext()
- android学习—— context 和 getApplicationContext()
- android学习—— context 和 getApplicationContext()
- android学习—— context 和 getApplicationContext()
- android学习—— context 和 getApplicationContext()
- android学习—— context 和 getApplicationContext()
- android学习—context 和 getApplicationContext()
- iOS APP开发--环境准备 - 黑苹果篇
- oracle密码过期ORA-28002
- 对private内存、virtual内存的一些讲解
- log4j日志级别的选择:Debug、Info、Warn、Error还是Fatal
- chapter3 结构体 共用体与枚举
- android学习—— context 和 getApplicationContext()
- 远程服务器,电脑端设置
- MySQL创建、删除、重建和查看索引命令
- poj3751-输入输出格式~水题
- android 设置控件的透明度
- 【SSH进阶之路】深入源码,详解Struts基本实现流程(七)
- was jax-ws
- 监视线程迁移
- django+nginx_uwsgi部署