2012年6月15日 星期五

[Android] Context

public abstract class Context
  • 管理 global application 資訊的 interface,是由 Android System 實作。
    • Interface to global information about an application environment. This is an abstract class whose implementation is provided by the Android system.
  • 可由此取得 application-specific 的 resources and classes。
    • It allows access to application-specific resources and classes, as well as up-calls for application-level operations such as launching activities, broadcasting and receiving intents, etc.

getApplicationContext()
  • 在啟動 app 時,預設會啟動 Application,也就是 AndroidManifest.xml 中的 <application>,因此也能自己實作指定在此 tag 中,替代此預設。
  • 回傳所在 process 中的 global application context。
    • Return the context of the single, global Application object of the current process.
  • 應被使用在當 lifecycle 不和當前 component 綁在一起時。
    • 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.
ex: 
  • registerReceiver(BroadcastReceiver, IntentFilter)
    • 如果使用的是 Activity context,這個 receiver 就是被註冊在此 Activity,所以你必須在此 Activity destroy 前 unregister 此 receiver,若沒有這樣做則會發生 exception。
      • 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.
    • 如果是使用 Application context,這個 receiver 是和 application 相關連,因此不會被 unregistered,但有可能會造成 leak。
      • However using the ApplicationContext elsewhere can easily lead to serious leaks if you forget to unregister, unbind, etc.
  • 使用在 DB 操作時。


* Reference
- 求getApplicationContext用法-Android 问题&解答-eoeAndroid开发者社区 - Powered by Discuz!
谈谈Android里的Context的使用!!! - Android_Tutor的专栏 - 博客频道 - CSDN.NET

沒有留言:

張貼留言