如何解决涉及此主题Android的内存泄漏?如何解决、此主题、内存、Android

2023-09-07 15:46:48 作者:谎友

于是我发现,用 MAT 我保持创建多个主题 surfaceCreate

So I've found, with the MAT that I keep creating multiple Threads with every surfaceCreate

我想我需要这些线程,虽然,但这种方法会导致 ViewThread 的多个实例,当用户浏览通过我的应用程序,这是一个内存泄漏。

I think I need these threads, though, but this method causes multiple instances of ViewThread, as a user navigates through my app, which is a memory leak.

我如何重新安排我的线程的创建和处理,以便这不会发生,或者我怎么能发生停止泄漏的方式?

How can I reorganize the way my threads are created and handled so that this doesn't happen, or how can I stop the leak from occurring?

@Override
public void surfaceCreated(SurfaceHolder holder) {
    loading=false;
    if (!mThread.isAlive()){
        mThread = new ViewThread(this);
        mThread.setMenuRunning(true);
        mThread.start();
    }
}

@Override
public void surfaceDestroyed(SurfaceHolder holder) {

    if (mThread.isAlive()){ 
        mThread.setMenuRunning(false);
    }
}

我打开,从我的游戏职业活动五次航行了,这是在显示的内容MAT

I opened and navigated away from the Career Activity of my game five times, and this is what shows up on the MAT

编辑:我自从发现,根据 surfaceDestroyed 我的线程的破坏是不可靠的。我现在从一个不同的方法调用相应的线程调用破坏,引发的onPause

I've since found that depending on surfaceDestroyed for the destruction of my threads is unreliable. I now call the appropriate thread-destroying calls from a different method, triggered onPause.

推荐答案

您应该使用的WeakReference引用职业生涯中的主题。这样的引用将被清除时,有对事业没有更多的硬引用。

You should use a WeakReference to reference the Career in your Thread. This way the reference will be cleared when there are no more hard references to the Career.

您可以通过右键单击事业和路径选择与GC根,然后用所有引用跟踪MAT的所有引用。这将显示你的路径(S),以保留在内存中的对象。请确保你要么清除这些引用,当你在做的活动或利用在WeakReferences的有GC自动清除它们。

You can track all references in MAT by right clicking the career and choosing Path To GC Roots, then with all references. This will show you the path(s) to the object retained in memory. Make sure you either clear those references when you are done with the activity or make use of WeakReferences to have the GC clear them automatically.

 
精彩推荐
图片推荐