zoukankan      html  css  js  c++  java
  • getApplicationContext()、Activity.this、 getBaseContext区别

     

    getApplicationContext()返回应用的上下文,生命周期是整个应用,应用退出它才被摧毁

    Activity.this 返回当前activity的上下文,属于activity ,activity destory,它也被摧毁

    getBaseContext()  the base context as set by the constructor or setBaseContext

     

    Context

    public abstract Context getApplicationContext ()

      Return the context of the single, global Application object of the current process. This generally should only be used if you

    need a Context whose lifecycle is separate from the current context, that is tied to the lifetime of the process rather than the

    current component.

    Consider for example how this interacts with registerReceiver(BroadcastReceiver, IntentFilter):

    • If used from an Activity context, the receiver is being registered within that activity. This means that you are expected to

    unregister before the activity is done being destroyed; in fact if you do not do so, the framework will clean up your leaked

    registration as it removes the activity and log an error. Thus, if you use the Activity context to register a receiver that is

    static (global to the process, not associated with an Activity instance) then that registration will be removed on you at whatever

    point the activity you used is destroyed.

    • If used from the Context returned here(getApplicationContext), the receiver is being registered with the global state associated

    with your application.Thus it will never be unregistered for you. This is necessary if the receiver is associated with static data, not a

    particular component.However using the ApplicationContext elsewhere can easily lead to serious leaks if you forget to unregister, unbind, etc.

      AlertDialog.Builder builder = new AlertDialog.Builder(this)中,要求传递的参数就是一个context,在这里我们传入的是当前Activity。

    AlertDialog应该是属于当前Activity的,在Activity销毁的时候它也就销毁了,但是,如果传入this.getApplicationContext(),就表示它的生命周期是整个

    应用程序,这显然超过了它的生命周期了。所以,在这里我们只能使用当前Activity

    1.dialog = ProgressDialog.show(getBaseContext(), "", "正在刷新好友列表");

    出错:Unable to add window -- token null is not for an application

  • 相关阅读:
    <mvc:default-servlet-handler />说明
    sql server 数据库创建链接服务器访问另外一个sql server 数据库
    WebSocket实现简易聊天室
    WebSocket在建立连接时通过@PathParam获取页面传值
    Shiro密码处理
    Java enum应用小结
    Java8 Optional类使用小结
    Java中使用Jedis操作Redis
    前台图片Canvas压缩上传小结
    剪邮票
  • 原文地址:https://www.cnblogs.com/yuyutianxia/p/3499892.html
Copyright © 2011-2022 走看看