关于Android中的getApplicationContext的知识

Open Declaration Context android.content. ContextWrapper .getApplicationContext()

public Context getApplicationContext ()
Since: API Level 1

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, 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.

翻译:

  •  .如果在一个活动的上下文中这个方法被用到了,那么接收者被注册在这个活动之中。这意味着你预期在这个活动被完成前去注销它。如果你不这样做,该框架将清理你泄露的注册因为这个活动已经被消除,并被记录为一个错误。因此,如果你用这个活动的上下文去注册一个接收器的话,这个接收器是静态的(在全局过程中与一个活动的实例无关),无论这个活动是否被破坏,这个注册都将会被消除。

  •  如果从这个上下文被使用的情况下返回到了这里,那么这个接收器与你的程序相关联地在全局状态下被注册。因此这个接收器将永远不会被注销。如果一个接收器和静态数据相关联而不是一个特定的组件相关联,这是必要的。但是如果你忘记了注销或者解除绑定等,在一些地方使用getApplicationContext可能会造成严重的泄露。

 

 

 

getApplicationContext可以与Activity.this的Context进行对比理解:

 

getApplicationContext() 返回应用的上下文,生命周期是整个应用,应用摧毁它才摧毁
Activity.this的context 返回当前activity的上下文,属于当前activity ,当前activity 摧毁他就摧毁
getBaseContext()  返回由构造函数指定或setBaseContext()设置的上下文
this.getApplicationContext()取的是这个应 用程序的Context,Activity.this取的是这个Activity的Context,这两者的生命周期是不同 的,前者的生命周期是整个应用,后者的生命周期只是它所在的Activity。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值