Android crash when app is closed and reopened

前端 未结 3 1636
渐次进展
渐次进展 2020-11-28 07:47

I have a really simple android app that just displays a blank white screen. When I close the app by pressing the HOME button, then try to open the app again, it crashes and

3条回答
  •  不知归路
    2020-11-28 08:19

    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();
        }
    }
    

提交回复
热议问题