简体   繁体   中英

How To Return To The Main Activity After Destroying A SurfaceView?

My Activity

protected void onDestroy(){
    super.onDestroy();
    finish();
}
public void onPause(){
    super.onPause();
    gv.gameLoopThread.setRunning(false);
    finish();
}
public void redirectHome(){

    onDestroy();
    Intent intent=new Intent(PlayActivity.this, MainActivity.class);
    startActivity(intent);
}

My View's On Click.

if(gameover){
              //My Restart Button.
          if(x>(getWidth()*.39375) && x<(getWidth()*.625) &&
                  y>(getHeight()*.583333333) && y<(getHeight()*.654166667)){                  
              gameover=false;
              createSprites();
              destroyed=0;
          }
              //My Exit Button.
          if(x>(getWidth()*.39375) && x<(getWidth()*.625) &&
                  y>(getHeight()*.729166667) && y<(getHeight()*.791666667)){
              gameLoopThread.setRunning(false);
              new PlayActivity().redirectHome();
          }

      }

My restart button works, but my exit button causes my app to crash pointing the error at 'Intent intent=new Intent(PlayActivity.this, MainActivity.class);' and 'new PlayActivity().redirectHome();

Any help is appreciated.

You do nt must ot call "OnDestroy()" callback directly and also to call finish() in onDestroy() method.

In your case it would be better to change your code like to something like this:

protected void onDestroy(){
  super.onDestroy();
}
public void onPause(){
  super.onPause();
  gv.gameLoopThread.setRunning(false);

}
public void redirectHome(){
 Intent intent=new Intent(PlayActivity.this, MainActivity.class);
 startActivity(intent);
 finish();
}

Also one question: is this thing is really worked somehow? I'm asking this because finish() call in onPause() callback should close your activity even before it appears on the screen.

Anyway, check my code and comment about results)

EDIT: also you can't actually create instance of activity and call on of it's methods like new PlayActivity().redirectHome(); so you need a context of Аctivity to perform start of new activity or finish this one.

It seems that because you can onDestroy the activity reference PlayActivity.this becomes invalid or null

You can use the application context instead of PlayActivity.this to and start your activity with FLAG_ACTIVITY_NEW_TASK

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM