Android内存泄漏并带有静态final [英] Android memory leak with static final

查看:55
本文介绍了Android内存泄漏并带有静态final的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题在于使用显然会导致内存泄漏的静态最终常量:我一直在寻找有关如何避免在Android Apps中导致内存泄漏的信息.一个大问题是对常量使用私有static final.显然,这就是常量的定义方式.但是静态的final表示它在旋转后仍会徘徊,并且该Activity无法清除.

The question is on using static final constants which apparently causes memory leaks: I have been searching for information on how not to cause memory leaks in Android Apps. One big problem is using private static final for constants. Apparently that is how constants should be defined. But static final means it hangs around after a rotation and means the Activity cannot be cleared.

很明显,我误会了一些东西.我知道将变量放在Application上下文中可以使它们挂起而不会引起问题.

Obviously I am misunderstanding something. I know that putting variables in the Application context allows them to hang around without causing problems.

作为有关内存泄漏的一般问题:关于内存泄漏,有很多信息,但是我找不到任何可以将所有信息清楚地总结出来的信息.所有建议均已充分解释.

As a general question on memory leaks: There are lots of information on memory leaks, but I cannot find anything that sums up all the information clearly. Any recommendations where it is all fully explained.

推荐答案

此信息不正确.仅仅因为将变量标记为静态最终变量,就可以将其制成静态最终变量不会导致任何类型的内存泄漏.但这并不是说您不能通过这样做来造成内存泄漏.您要确保避免的一件事是创建一个上下文类型(例如活动)的静态变量.当您创建对上下文的静态引用时,可能会导致内存泄漏.静态变量意味着整个应用程序以及该类的实例中只有该变量的一个副本.这也意味着它将一直保留在内存中,直到将其明确清除或关闭应用程序为止.静态变量是类级别的变量,并且不附加到对象的任何特定实例.例如,当您创建公共静态最终字符串myString ="Hello""时,您将永远不会造成内存泄漏.与使用'public final string myString ="Hello"'相比,这种定义常量的方式实际上将节省内存,因为如果没有静态的话,将为该类的每个实例创建一个存储位置来存储该字符串,而不是为所有实例仅创建一个副本使用.

This information is incorrect. Making a variable static final will not cause any kind of memory leaks just because it was marked static final. That is not to say you can't create memory leaks by doing that though. One thing you want to make sure to avoid is creating a static variable that is of type context (such as activity). When you create a static reference to a context you are possibly creating a memory leak. A static variable means there is only one copy of that variable for your entire application and across instances of that class. It also means that it will remain in memory until it is explicitly cleared or the application is shutdown. Static variables are class level variables and are not attached to any specific instance of an object. When you create for example a 'public static final string myString = "Hello"' you will never be causing a memory leak. This way of define a constant will actually save memory vs using 'public final string myString = "Hello"' because without static a memory location will be created to store that string for every instance of this class instead of just having one copy for all instances to use.

这篇关于Android内存泄漏并带有静态final的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆