【问题标题】:Android Surfaceview Threads and memory leaksAndroid Surfaceview 线程和内存泄漏
【发布时间】:2011-11-05 20:34:50
【问题描述】:

我在 android 中创建游戏,我注意到游戏存在内存泄漏。 Iv 设法将内存泄漏隔离到一个较小的应用程序中,以便我可以很好地了解如何解决它。

应用程序使用一个surfaceview 作为它的视图,并且有一个线程连接到它上面,以便在屏幕上进行所有的绘图。当我开始一项新活动并关闭我当前使用的活动时,就会发生内存泄漏。当我在我的测试应用程序上进行内存转储时,我可以看到这一点,因为它所做的只是打开和关闭一个活动(活动 a -> 活动 b -> 活动 a)。 Iv 有点想不出如何解决这个问题,因为 iv 尝试将我创建的所有对视图(在线程内)的引用归零,iv 尝试在销毁视图时从表面视图中删除回调,以及在活动内部,它似乎没有任何区别。

MemoryLeakActivity.java

package memory.leak;

import memory.leak.view.MemoryLeak;
import android.app.Activity;
import android.os.Bundle;

public class MemoryLeakActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(new MemoryLeak(this));
    }
}

MemoryLeakViewThread.java

package memory.leak.thread;

import memory.leak.view.MemoryLeak;
import android.view.SurfaceHolder;
import android.graphics.Canvas;


public class MemoryLeakViewThread extends Thread {
    private MemoryLeak view;
    private boolean run =false;

    public MemoryLeakViewThread(MemoryLeak view) {
        this.view =view;
    }

    public void setRunning(boolean run) {
        this.run =run;
    }

    @Override
    public void run() {
        Canvas canvas =null;
        SurfaceHolder holder =this.view.getHolder();
        while(this.run) {
            canvas =holder.lockCanvas();
            if(canvas !=null) {
                this.view.onDraw(canvas);
                holder.unlockCanvasAndPost(canvas);
            }
        }
        holder =null;
        this.view =null;
    }
}

MemoryLeak.java

package memory.leak.view;

import memory.leak.TestActivity;
import memory.leak.thread.MemoryLeakViewThread;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Color;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.GestureDetector.OnGestureListener;


public class MemoryLeak extends SurfaceView implements SurfaceHolder.Callback, OnGestureListener {
    private GestureDetector gesture;
    private MemoryLeakViewThread vThread;
    private Context context;

    public MemoryLeak(Context context) {
        super(context);

        this.getHolder().addCallback(this);
        this.vThread =new MemoryLeakViewThread(this);

        this.gesture =new GestureDetector(this);
        this.context =context;
    }

    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {}

    public void surfaceCreated(SurfaceHolder holder) {
        if(!this.vThread.isAlive()) {
            this.vThread =new MemoryLeakViewThread(this);
            this.vThread.setRunning(true);
            this.vThread.start();
        }
    }

    public void surfaceDestroyed(SurfaceHolder holder) {
        boolean retry = true;

        if(this.vThread.isAlive()) {
            this.vThread.setRunning(false);
            while(retry) {
                try {
                    this.vThread.join();
                    retry =false;
                } catch(Exception ee) {}
            }
        }

        this.vThread =null;
        this.context =null;
    }

     public boolean onTouchEvent(MotionEvent event) {
         return this.gesture.onTouchEvent(event);
     }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    }

    @Override
    public void onDraw(Canvas canvas) {
        canvas.drawColor(Color.WHITE);
    }   

    @Override
    public boolean onDown(MotionEvent e) {
        return true;
    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        return false;
    }

    @Override
    public void onLongPress(MotionEvent e) {}

    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
        return false;
    }

    @Override
    public void onShowPress(MotionEvent e) {}

    @Override
    public boolean onSingleTapUp(MotionEvent e) {
        Intent helpScreenIntent =new Intent(this.context, TestActivity.class);
        this.context.startActivity(helpScreenIntent);

        if (this.context instanceof Activity)
            ((Activity) this.context).finish();

        return true;
    }
}

TestActivity.java

package memory.leak;

import memory.leak.view.Test;
import android.app.Activity;
import android.os.Bundle;

public class TestActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(new Test(this));
    }
}

TestViewThread.java

package memory.leak.thread;

import memory.leak.view.Test;
import android.view.SurfaceHolder;
import android.graphics.Canvas;


public class TestViewThread extends Thread {
    private Test panel;
    private boolean run =false;

    public TestViewThread(Test panel) {
        this.panel =panel;
    }

    public void setRunning(boolean run) {
        this.run =run;
    }

    @Override
    public void run() {
        Canvas canvas =null;
        SurfaceHolder holder =this.panel.getHolder();
        while(this.run) {
            canvas =holder.lockCanvas();
            if(canvas !=null) {
                this.panel.onDraw(canvas);
                holder.unlockCanvasAndPost(canvas);
            }
        }
        holder =null;
        this.panel =null;
    }
}

Test.java

package memory.leak.view;

import memory.leak.MemoryLeakActivity;
import memory.leak.thread.TestViewThread;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Color;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.GestureDetector.OnGestureListener;


public class Test extends SurfaceView implements SurfaceHolder.Callback, OnGestureListener {
    private GestureDetector gesture;
    private TestViewThread vThread;
    private Context context;

    public Test(Context context) {
        super(context);

        this.getHolder().addCallback(this);
        this.vThread =new TestViewThread(this);

        this.gesture =new GestureDetector(this);
        this.context =context;
    }

    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {}

    public void surfaceCreated(SurfaceHolder holder) {
        if(!this.vThread.isAlive()) {
            this.vThread =new TestViewThread(this);
            this.vThread.setRunning(true);
            this.vThread.start();
        }
    }

    public void surfaceDestroyed(SurfaceHolder holder) {
        boolean retry = true;

        if(this.vThread.isAlive()) {
            this.vThread.setRunning(false);
            while(retry) {
                try {
                    this.vThread.join();
                    retry =false;
                } catch(Exception ee) {}
            }
        }

        this.vThread =null;
        this.context =null;
    }

     public boolean onTouchEvent(MotionEvent event) {
         return this.gesture.onTouchEvent(event);
     }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    }

    @Override
    public void onDraw(Canvas canvas) {
        canvas.drawColor(Color.RED);
    }   

    @Override
    public boolean onDown(MotionEvent e) {
        return true;
    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        return false;
    }

    @Override
    public void onLongPress(MotionEvent e) {}

    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
        return false;
    }

    @Override
    public void onShowPress(MotionEvent e) {}

    @Override
    public boolean onSingleTapUp(MotionEvent e) {
        Intent helpScreenIntent =new Intent(this.context, MemoryLeakActivity.class);
        this.context.startActivity(helpScreenIntent);

        if (this.context instanceof Activity)
            ((Activity) this.context).finish();

        return true;
    }
}

--编辑-- 我对视图类的surfaceDestroyed(SurfaceHolder holder) 进行了更改,以便当线程被告知停止时它将设置线程必须为空的视图。我所做的更改是

public void surfaceDestroyed(SurfaceHolder holder) {
        boolean retry = true;

        if(this.vThread.isAlive()) {
            this.vThread.setRunning(false);
            while(retry) {
                try {
                    this.vThread.join();
                    retry =false;
                } catch(Exception ee) {}
            }
            this.vThread.setRunning(false, null);
        }

        this.vThread =null;
        this.context =null;
        this.gesture =null;
    }

你还需要把surfaceCreated(SurfaceHolder holder)方法改成

public void surfaceCreated(SurfaceHolder holder) {
        if(!this.vThread.isAlive()) {
            this.vThread =new MemoryLeakViewThread();
            this.vThread.setRunning(true, this);
            this.vThread.start();
        }
    }

那么在线程类上我们需要更改以下内容

public MemoryLeakViewThread() {
    }

    public void setRunning(boolean run) {
        this.run =run;
    }

    public void setRunning(boolean run, MemoryLeak view) {
        this.run =run;
        this.view =view;
    }

这样做似乎解决了问题,现在唯一的问题是线程似乎留在内存中,由于线程类和线程组。但我认为这可能是由于调试器造成的。

【问题讨论】:

  • 添加异常和堆栈跟踪将有助于了解问题。
  • Iv 通过在设置线程的运行状态时传递视图,然后在我将运行状态设置为 false 时将其设置为 null 来解决大部分内存泄漏问题。这已经从内存中删除了活动和视图,现在唯一留下的是似乎卡在线程组类中的线程。我确实记得读过一些关于线程的东西,如果没有开始,我会卡在那里,我现在找不到指向它的链接。
  • code.google.com/p/android/issues/detail?id=7979 就是这样。至于堆栈跟踪,您希望我在哪里添加异常?它不会抛出任何东西,它最终会在内存不足时出现,但由于我的测试应用程序没有使用太多内存,因此需要一段时间。我正在使用 MAT 分析堆转储,以便查看内存中卡住了什么
  • 出于兴趣,我运行了您的代码,并添加了一些日志记录。您说这些活动已被删除 - 但是,如果我在命令行上运行“adb shell dumpsys meminfo memory.leak”,我会在每个开关上看到一个新活动添加到堆栈中,即使调用了 onDestroy() 并且线程循环似乎退出确定。所以我不知道如何解决它,但我认为这可能对你有用。
  • 是的,这就是我最初遇到的问题,我设法使它达到一定程度,以便线程只保留在内存中,我认为这与调试器有关。

标签: android multithreading memory-leaks surfaceview


【解决方案1】:

在 onSurfaceCreated 中创建线程时,不应在构造函数中创建新线程。将您的代码与我的示例进行比较:How can I use the animation framework inside the canvas?

【讨论】:

  • 尝试了你所说的并将线程的创建从构造函数方法中删除,并将其放在 Surfacecreated 方法中。这阻止了线程卡在内存中。 :D 我的所有记忆问题现在都已修复。
【解决方案2】:

如您所见:

http://developer.android.com/resources/articles/avoiding-memory-leaks.html

在 Android 中引发内存泄漏的最简单方法是向视图的构造函数传递整个 Activity 而不是应用程序上下文。您是否尝试更改此行:

setContentView(new MemoryLeak(this));

进入这个:

setContentView(new MemoryLeak(Context.getApplicationContext()));

?

希望对你有帮助。

【讨论】:

  • 你显然没有尝试过,或者你会看到当你尝试编译一个对非静态方法的静态引用时会发生什么。
猜你喜欢
  • 2017-02-04
  • 2014-10-29
  • 2013-12-18
  • 1970-01-01
  • 2016-12-09
  • 2020-08-08
  • 2012-02-17
  • 2020-12-08
  • 2018-06-19
相关资源
最近更新 更多