在android中使用Context哪个更高效?

发布于 2024-12-03 20:52:25 字数 73 浏览 0 评论 0原文

getApplicationContext() 和 this(扩展 Activity)哪个更有效?为什么?

Which is more efficient between getApplicationContext() or this (extends Activity)? Why?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

梦旅人picnic 2024-12-10 20:52:25

据我所知,效率上没有区别(如果有的话应该可以忽略不计)。引入getApplicationContext()的原因是为了避免内存泄漏。

例如,如果您将 Activity 作为上下文传递给某个长期存在的对象,并且该对象将在其生命周期内保留此上下文,那么您就会遇到问题。例如,如果配置发生更改或活动被销毁,则该活动将被视为死亡(作为组件)。但由于至少有一个对这个旧 Activity 对象的引用,它不会被垃圾收集器清理。

因此,在这种情况下,当您需要存储更长时间的上下文时,您应该使用 context.getApplicationContext() 而不是直接保存上下文。而且由于应用程序对象在进程运行时始终被视为“活动”,因此不存在内存/资源泄漏。

There is no difference in terms of efficiency as far as I know (and if there is it should be neglectable). The reason why getApplicationContext() was introduced is to avoid memory leaks.

For example, if you pass Activity as context to some long living object and this object is going to keep this context for it lifetime, you'll have a problem. For example, if configuration is changed or activity is destroyed, the activity is considered dead (as component). But since there is at least one reference to this old Activity object it will not be cleaned up by garbage collector.

So, in such cases when you need to store context for longer time you should use context.getApplicationContext() instead of directly saving context. And because Application object is always considered "alive" while process is running, there is no memory/resource leaks.

一萌ing 2024-12-10 20:52:25

据我所知,使用 getApplicationContext() 更有效,因为它是整个应用程序的主要上下文,而不是您正在运行的每个活动的上下文实例。

阅读此内容: http://android-developers.blogspot.com/ 2009/01/avoiding-memory-leaks.html ,然后你就知道我在说什么了

using getApplicationContext() is more efficient as i know, because its the major context for the whole application, not instance of context for every activity you are running.

read this : http://android-developers.blogspot.com/2009/01/avoiding-memory-leaks.html , then you will know what am talking about

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文