java – 为什么对Context的引用是内存泄漏?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java – 为什么对Context的引用是内存泄漏?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2514字,纯文字阅读大概需要4分钟。
内容图文
根据Romain Guy这种代码很容易因内存泄漏而导致内存泄漏
…. views have a reference to the entire activity and therefore to
anything your activity is holding onto; usually the entire View
hierarchy and all its resources.
@Override
protected void onCreate(Bundle state) {
super.onCreate(state);
TextView label = new TextView(this);
label.setText("Leaks are bad");
setContentView(label);
}
我不清楚这一点.
假设具有1个活动的应用程序,这是最长寿命的对象,可以根据需要重新创建.这意味着它的所有实例字段(可以且通常是视图)可以随时为空.
并且任何静态实例字段将与活动本身持续相同的持续时间.
那么我们如何使用上面或下面的代码来获取内存泄漏:
private static Drawable sBackground;
@Override
protected 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
不它不是.您的流程中还有其他对象(例如,应用程序,内容提供程序)将比活动实例更长.
特别要注意的是,默认情况下,在配置更改(例如,屏幕旋转)时,活动会被销毁并重新创建.
And any static instance field will live for the same duration as the activity itself.
不会.只要流程在周围,静态字段就会出现.您的活动实例可能比这更短.
So how can we get a memory leak with code like the above or the following:
您的第一个示例中没有静态字段.
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.)
而且,如果您将LeakCanary添加到项目中,您会看到泄漏.
那么,让我们来看看:
>用户点击应用的主屏幕启动器图标,该图标与此活动相关联
>您的流程已开始
>您的活动实例已创建,然后使用onCreate()调用
> sBackground为null,因此您可以为其指定getDrawable()结果
>您的活动UI出现在屏幕上
>使用者打喷嚏并意外地旋转设备的屏幕,作为对打喷嚏起反应的一部分
>您的旧活动实例已被销毁
>创建一个新的活动实例,然后使用onCreate()调用
> sBackground不为null,因此您将单独留下sBackground
你有泄漏.正如Romain所解释的那样,sBackground对你的原始活动实例有一个非常明显的引用.因此,现在您有两个此活动的未完成实例:泄漏的原始文件,以及由于配置更改而创建的新原始实例.
内容总结
以上是互联网集市为您收集整理的java – 为什么对Context的引用是内存泄漏?全部内容,希望文章能够帮你解决java – 为什么对Context的引用是内存泄漏?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。