Android crash when app is closed and reopened

I’ve answered a question like this here.

The error you’re getting is probably caused by your Thread (without seeing the full Logcat it’s hard to tell though). You’re starting it every time the surface is created, which will make your application crash because you can’t call Thread.start() twice. Look at my link above for a more in-depth description of the problem and how you should solve it.

Since my explanation wasn’t enough I will post the whole solution:

Inside your Runnable/Thread:

private Object mPauseLock = new Object();  
private boolean mPaused;

// Constructor stuff.      

// This should be after your drawing/update code inside your thread's run() code.
synchronized (mPauseLock) {
    while (mPaused) {
        try {
            mPauseLock.wait();
        } catch (InterruptedException e) {
        }
    }
}

// Two methods for your Runnable/Thread class to manage the thread properly.
public void onPause() {
    synchronized (mPauseLock) {
        mPaused = true;
    }
}

public void onResume() {
    synchronized (mPauseLock) {
        mPaused = false;
        mPauseLock.notifyAll();
    }
}

In your SurfaceView class:

private boolean mGameIsRunning;

@Override
public void surfaceCreated(SurfaceHolder holder) {
    // Your own start method.
    start();
}

public void start() {
    if (!mGameIsRunning) {
        thread.start();
        mGameIsRunning = true;
    } else {
        thread.onResume();
    }
}

Leave a Comment