Android crash when app is closed and reopened

前端 未结 3 1601
渐次进展
渐次进展 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:18

    Here is a simple solution which may be acceptable in some cases, like a background animation screen and activities which states do not need to be restored - the surface view activity needs to finish on pause.

    protected void onPause()  { 
     super.onPause(); 
     finish();
    } 
    

    The better solution is to move the creation of the thread from the constructor into on surfaceCretaed like this:

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
      _thread = new TutorialThread(holder, this);
      _thread.setRunning(true);
      _thread.start(); 
    }
    

    Then in the thread loop create a pause flag:

    if(!pause){
      _panel.onDraw(c); 
    }
    

    finally in onPause and onRestore for the activity set the pause flag:

       protected void onResume() {
                super.onResume();
                pause = false;    
            }
    
            protected void onPause()  {   
                super.onPause();   
                pause = true;   
            } 
    

    When the user clicks Home button surfaceDestroyed is invoked which will shut down the current thread "_thread". When he returns to the app, surfaceCreated will assign the reference "_thread" to a new thread, while the old thread object will be removed by the garbage collector.

提交回复
热议问题