End SurfaceView and GameThread on exiting app End SurfaceView and GameThread on exiting app multithreading multithreading

End SurfaceView and GameThread on exiting app


The Surface underlying the SurfaceView gets destroyed between onPause() and onDestroy() in the app lifecycle. Send a message to your renderer thread in onPause(), and wait for the thread to shut down.

For an example, see the "Hardware scaler exerciser" activity in Grafika. It starts the render thread in the SurfaceHolder's surfaceCreated() callback.

Update: it felt weird to start the thread in surfaceCreated() and stop it in onPause(), so after a bit of reshuffling HardwareScalerActivity now stops the thread in surfaceDestroyed(). (The SurfaceView documentation is a bit ambiguous -- it says the Surface is valid "between surfaceCreated() and surfaceDestroyed()" -- but looking at the SurfaceView implementation this appears to be the expected usage.)

Update 2: I updated the code some more after finding cases it didn't handle well. There's now a 60-line megacomment in the sources, which can also been seen in my answer to a similar question.

Update 3: The mega-comment turned into an architecture doc appendix. Grafika's "hardware scaler exerciser" activity demonstrates approach #2, while "texture from camera" demonstrates approach #1.


Well you can make changes to your code like this.

In GameView

@Override    public void surfaceCreated(SurfaceHolder holder) {        MainActivity obj=new MainActivity();        stop=obj.getBoolean(); //receive status of boolean from main activity        //stop is boolean set if backPressed in main activity        if(!stop){         gameThread.setRunning(true);        gameThread.start();        }        else            gameThread.setRunning(false);    }

In MainActivity

public Boolean getBoolean(){return stop;    } public void setBoolean(Boolean bools){stop=bools;}@Overridepublic void onBackPressed() {// TODO Auto-generated method stubsuper.onBackPressed();stop=true;setBoolean(stop);try{Thread.sleep(200); // Be safeside and wait for Game thread to finish}catch(Exception e){e.printStackTrace();}MainActivity.finish();}

Call setBoolean once before backPress else it will give error. Make amendments to code as per your needs.

Hope it helps. Cheers. :)