android获取context的方法,android中获取context的方法们的区别与联系

66b52468c121889b900d4956032f1009.png

8种机械键盘轴体对比

本人程序员,要买一个写代码的键盘,请问红轴和茶轴怎么选?

getActivity():

This method gives the context of the Activity. You can use it is like the yourActivity.this. The method getActivity() is normally used in fragments to get the context of the activity in which they are inserted or inflated.

getContext():

Returns the context the view is currently running in. Usually the currently active Activity. getContext() is not defined in an Activity. It’s used in a View (or View subclass) to get a reference to the enclosing context (an Activity).

Difference between getActivity() and getContext()

Activity is a subclass of Context.

When you call getActivity() you get an Activity which is a Context as well. But when you call getContext() you will get a Context which might not be an Activity.

When using newer version of Support Library, when Fragment is not hosted by an Activity you can get different objects when calling getActivity() and getContext().

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 call getApplicationContext() and cast it to your application, because it may not be the application instance (which you obviously experienced with the test framework).

getApplicationContext():

Activity.getApplicationContext(): Returns the context for the entire application (the process all the Activities are running inside of). Use this instead of the current Activity context if you need a context tied to the lifecycle of the entire application, not just the current Activity.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值