我想避免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--;
}
}
答案 0 :(得分:0)
您可以在Activity中覆盖方法“OnBackPressed”并在那里执行任何自定义逻辑。以下是文档https://developer.android.com/reference/android/app/Activity.html#onBackPressed()
的链接答案 1 :(得分:0)
如果你的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--;
}
}