根据Romain Guy这种代码很容易因内存泄漏而导致内存泄漏
…. vIEws have a reference to the entire activity and therefore to
@H_404_9@
anything your activity is holding onto; usually the entire VIEw
hIErarchy and all its resources.@OverrIDeprotected voID onCreate(Bundle state) { super.onCreate(state); TextVIEw label = new TextVIEw(this); label.setText("Leaks are bad"); setContentVIEw(label);}
我不清楚这一点.
假设具有1个活动的应用程序,这是最长寿命的对象,可以根据需要重新创建.这意味着它的所有实例字段(可以且通常是视图)可以随时为空.
并且任何静态实例字段将与活动本身持续相同的持续时间.
那么我们如何使用上面或下面的代码来获取内存泄漏:private static Drawable sBackground;@OverrIDeprotected voID onCreate(Bundle state) { super.onCreate(state); TextVIEw label = new TextVIEw(this); label.setText("Leaks are bad"); if (sBackground == null) { sBackground = getDrawable(R.drawable.large_bitmap); } label.setBackgroundDrawable(sBackground); setContentVIEw(label);}
解决方法:
Assuming an application with 1 activity, this is the longest lived object
@H_404_9@不它不是.您的流程中还有其他对象(例如,应用程序,内容提供程序)将比活动实例更长.
特别要注意的是,默认情况下,在配置更改(例如,屏幕旋转)时,活动会被销毁并重新创建.
And any static instance fIEld will live for the same duration as the activity itself.
@H_404_9@不会.只要流程在周围,静态字段就会出现.您的活动实例可能比这更短.
So how can we get a memory leak with code like the above or the following:
@H_404_9@您的第一个示例中没有静态字段.
Romain Guy解释了the blog post that you linked to中的第二个场景:
This code is very fast and also very wrong; it leaks the first activity created upon the first screen orIEntation change. When a Drawable is attached to a vIEw, the vIEw is set as a callback on the drawable. In the code snippet above, this means the drawable has a reference to the TextVIEw which itself has a reference to the activity (the Context) which in turns has references to pretty much anything (depending on your code.)
@H_404_9@而且,如果您将LeakCanary添加到项目中,您会看到泄漏.
那么,让我们来看看:
>用户点击应用的主屏幕启动器图标,该图标与此活动相关联
>您的流程已开始
>您的活动实例已创建,然后使用onCreate()调用
> sBackground为null,因此您可以为其指定getDrawable()结果
>您的活动UI出现在屏幕上
>使用者打喷嚏并意外地旋转设备的屏幕,作为对打喷嚏起反应的一部分
>您的旧活动实例已被销毁
>创建一个新的活动实例,然后使用onCreate()调用
> sBackground不为null,因此您将单独留下sBackground你有泄漏.正如Romain所解释的那样,sBackground对你的原始活动实例有一个非常明显的引用.因此,现在您有两个此活动的未完成实例:泄漏的原始文件,以及由于配置更改而创建的新原始实例.
总结以上是内存溢出为你收集整理的java – 为什么对Context的引用是内存泄漏?全部内容,希望文章能够帮你解决java – 为什么对Context的引用是内存泄漏?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)