简体   繁体   English

Android:试图产生内存泄漏

[英]Android : trying to generate a memory leak

I am using the following post to generate a memory leak in a test application 我正在使用以下帖子在测试应用程序中生成内存泄漏

http://android-developers.blogspot.com/2009/01/avoiding-memory-leaks.html http://android-developers.blogspot.com/2009/01/avoiding-memory-leaks.html

I am using android studio memory profiler and allocation tracker to track the object allocation. 我正在使用android studio内存分析器和分配跟踪器来跟踪对象分配。 I am able to see activity instances created while rotating the screen multiple times. 我能够看到多次旋转屏幕时创建的活动实例。 But when I click on "Initiate GC" on android studio all these instances are garbage collected though they hold a static reference to the drawable object. 但是,当我单击android studio上的“启动GC”时,所有这些实例均被垃圾回收,尽管它们持有对drawable对象的静态引用。 I was expecting these activity objects to be retained and will cause an "Out of memory" exception. 我期望保留这些活动对象,并且将导致“内存不足”异常。 Below is the code I have used : 以下是我使用的代码:

   @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       TextView textView = new TextView(this);
        textView.setText("Hello View");
        if(sBackground == null) {
            sBackground = ContextCompat.getDrawable(this,R.drawable.back1mb);
        }
        mTextView = (TextView) findViewById(R.id.txtView);

        textView.setBackgroundDrawable(sBackground);
        setContentView(textView);

    }

The problem is, the blog post you've referenced is very old, and the Android SDK has changed a lot since it was written. 问题是,您引用的博客文章很老,自编写以来,Android SDK发生了很大变化。 In the early days, as the tutorial says: 就像教程中所说的,在早期:

When a Drawable is attached to a view, the view is set as a callback on the drawable. 当将Drawable附加到视图时,该视图将设置为可绘制对象上的回调

However, this isn't true for more recent versions of the Android SDK. 但是,最新版本的Android SDK并非如此。

The code for the early version of Drawable.setCallback was (see link ): Drawable.setCallback的早期版本的代码是(参见链接 ):

public final void setCallback(Callback cb) {
    mCallback = cb;
}

But it now uses a WeakReference (see link ), so won't leak any more: 但是现在它使用了WeakReference (请参阅链接 ),因此不再泄漏:

public final void setCallback(Callback cb) {
     mCallback = new WeakReference<Callback>(cb);
}

You could build against an old version of Android to see the leak behaviour in the blog, or use a different means of creating a leak. 您可以使用旧版本的Android进行构建,以查看博客中的泄漏行为,也可以使用其他方法来创建泄漏。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM