当前位置: 代码迷 >> Android >> 关于Android中的getApplicationContext的学问
  详细解决方案

关于Android中的getApplicationContext的学问

热度:42   发布时间:2016-05-01 11:21:19.0
关于Android中的getApplicationContext的知识
Open DeclarationContext android.content.ContextWrapper.getApplicationContext()

publicContextgetApplicationContext()

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 withregisterReceiver(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。

 

  相关解决方案