在android中使用Context哪个更高效?
getApplicationContext()
和 this(扩展 Activity)哪个更有效?为什么?
Which is more efficient between getApplicationContext()
or this (extends Activity)? Why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
据我所知,效率上没有区别(如果有的话应该可以忽略不计)。引入
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 oldActivity
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.据我所知,使用 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