youngjuning / issues

一寸欢喜 - 怕什么真理无穷,进一寸有一寸的欢喜
https://youngjuning.js.org
44 stars 4 forks source link

Android中this和getApplicationContext()两种上下文的区别 #186

Closed youngjuning closed 4 years ago

youngjuning commented 5 years ago
  1. getApplicationContext() 返回 Context
  2. activity.this 代表的就是当前的 activity ,继承 context ,父类当中有的方法子类中一定有,子类中有的方法父类中不一定有,在用 getApplicationContext() 一定能使用 activity.this ,但是能用activity.this 不一定能使用 getApplicationContext()
  3. 报错:android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application,是因为没有添加窗口。
  4. 在使用对话框的时候,必须告诉对话框,要挂载哪个 activity ,也是告诉对话框应用在哪个 activity 中显示
  5. 在使用跟对话框相关的操作的时候必须使用 activity.this 不能使用 getApplicationContext()
  6. getContext() : 返回 Context ,一般用在单元测试中或者是自定义控件,其实和 getApplicationContext() 一样操作
  7. this: 代表当前,在 Activity 当中就是代表当前的 Activity ,换句话说就是 Activity.thisActivity 当中可以缩写为 thisgetApplicationContext() :生命周期是整个应用,应用摧毁,它才摧毁,能用 getApplicationContext() 的,百分百能用 this,但是反过来不一定可以
youngjuning commented 5 years ago

https://blog.csdn.net/zwj540469505/article/details/51420070