Context的区别

本文深入探讨了Android应用中Context的两种类型:Activity和Application的区别,强调了在不同场景下使用Application Context的重要性。讨论了使用Application Context时遇到的问题,并提供了在Android开发中正确使用Context的建议。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

[quote]
In a regular Android application, you usually have two kinds of Context, Activity and Application.

Reading the article a little bit further tells about the difference between to the two and why you might want to consider using the application Context (Activity.getApplicaitonContext()) rather than using the Activity context ("this"). Basically the Application context is associated with the Applicaiton and will always be the same throughout the life cycle of you app, where as the Activity context is associated with the activity and could possible be destroyed many times as the activity is destroyed during screen orientation changes and such.

I couldn't find really anything about when to use getBaseContext() other than a for a one liner from Dianne Hackborn, one of the Google engineers working on the Android SDK:

Don't use getBaseContext(), just use the Context you have.

That was from a post on the android-developers newsgroup, you may want to consider asking your question there as well because a handful of the people working on Android actual monitor that newsgroup and answer questions.

So overall it seems preferable to use the global application context when possible.


I got bad window token errors when using application context to Progress Dialog. So i used activity context instead.
[/quote]

在一般android程序中,通常有两种类型的Context:Activity类型以及Application类型。

通过更深的了解,你也许会在使用Application类型的Context时比使用Activity类型的更小心。基本上,Application类型的Context会伴随程序的整个生命周期,而Activity类型的Context则与Activity的状态相关,它会随着Activity的消亡而消亡。例如当屏幕方向发生变化时。


我找不到更多关于getBaseContext()的相关用法,除了google Android SDK工程师 Dianne Hackborn的一句话
不要使用getBaseContext(),使用你手头上的Context。

这句话来自android-developers 新闻组,许许多多的android开发者都在关注着新闻组,你也可以在那里提出自己的问题,有人会回答。

所以总的来说最好还是尽可能的使用Application类型的context。
我在使用ProgressDialog的时候使用 Application类型的Context 遇到了 bad window token errors。然后我用Activity类型的Context替代
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值