Android上下文

What is the difference between

  1. getApplicationContext()
  2. getBasecontext()
  3. getApplication()
  4. getParent()

Can you elaborate with one simple example?


1.getApplicationContext() 

getApplicationContext() Application context is associated with the Applicaition and will always be the same throughout the life cycle.

2.getBasecontext() 

getBasecontext() should not be used just use Context instead of it which is associated with the activity and could possible be destroyed when the activity is destroyed.

3.getApplication()

getApplication() is available to Activity and Services only. Although in current Android Activity and Service implementations, getApplication() and getApplicationContext() return the same object, there is no guarantee that this will always be the case (for example, in a specific vendor implementation). So if you want the Application class you registered in the Manifest, you should never callgetApplicationContext() and cast it to your application, because it may not be the application instance (which you obviously experienced with the test framework).

4.getParent() 

getParent() returns object of the activity if the current view is a child..In other words returns the activity object hosting the child view when called within the child.


参考资料地址:http://stackoverflow.com/questions/1026973/android-whats-the-difference-between-the-various-methods-to-get-a-context

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值