我想避免android用户玩我的游戏并获得游戏结束权,而他们只是单击后退按钮即可返回游戏。

这是从我的GameActivity跳转到新的GameOver Activity的代码。我可以使用什么命令?我只是想回到主要活动而不是gameActivity。

private void checkFails(){
    TextView failsleft = (TextView) findViewById(R.id.fails);
    if(fails < 1){
        failsleft.setText("Fails left: "+fails);
        Intent intent = new Intent(this, GameOverActivity.class);
        startActivity(intent);

    }else{
        failsleft.setText("Fails left: "+fails);
        fails--;
    }
}

最佳答案

如果您的GameActivity是由MainActivity启动的,则可以使用其他命令来告知主要活动游戏已结束。因此,您需要使用startActivityWithResult启动GameActivity。

在MainActivity中,使用startActivityForResult()启动GameActivity:

public class MainActivity extends AppCompatActivity {

    ...

    // Request code for handling the GameActivity result
    // make it final so it can be changed.
    private static final int gameOverRequestCode = 777;

    // Start GameActivity
    private void startTheGame() {
      Intent intent = new Intent(this, GameActivity.class);
      // start the GameActivity and wait for the result.
      startActivityForResult(intent, gameOverRequestCode);
    }


    @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
      switch (requestCode) {

        // Handle the result from GameActivity.
        // when the result is accepted from GameActivity, start the GameOverActivity.
        case gameOverRequestCode:
          if (resultCode == Activity.RESULT_OK) {
            Intent intent = new Intent(this, GameOverActivity.class);
            startActivity(intent);
          }
          break;
      }
    }

    ...
}


在GameActivity中,在游戏结束时发送结果:

private void checkFails(){
    TextView failsleft = (TextView) findViewById(R.id.fails);
    if(fails < 1){
        failsleft.setText("Fails left: "+fails);

        // Send the result back to main activity
        Intent i = getIntent();
        // you can add any extra here, for example, game state.
        // i.putExtra("extra_key", value);
        setResult(Activity.RESULT_OK, i);

        // Finish the GameActivity because we don't need it anymore.
        finish();

    }else{
        failsleft.setText("Fails left: "+fails);
        fails--;
    }
}

09-27 23:49