【发布时间】:2021-03-28 07:53:22
【问题描述】:
我有一个 MainActivity.java,如下所示:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_main);
}
public void startGame(View v){
Intent i = new Intent(MainActivity.this, StartGame.class);
startActivity(i);
}
我的 StartGame 类如下:
public class StartGame extends AppCompatActivity {
private Game game;
private Handler updateHandler;
public static Sound sound;
public static Activity activity = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
sound = new Sound(this);
game = new Game(this, 3, 0);
setContentView(game);
CreateHandler();
UpdateThread myThread = new UpdateThread(updateHandler);
myThread.start();
activity = this;
}
private void CreateHandler() {
updateHandler = new Handler() {
public void handleMessage(Message msg) {
game.invalidate();
game.update();
super.handleMessage(msg);
}
};
}
protected void onPause() {
super.onPause();
game.pauseGame();
}
protected void onResume() {
super.onResume();
game.resumeGame();
}
@Override
public void onBackPressed() {
super.onBackPressed();
}
}
我的问题是:
我在 MainActivity.java 中,我通过一个 Button 成功启动了 StartGame 的一个新实例(它用和 onDraw 触发了我的游戏)。现在,如果用户按下软后退按钮(导航栏),Activity 将关闭并出现 MainActivity 布局,但我仍然可以听到游戏在后台运行的声音(即使我转到主屏幕),表示活动仍在运行。
我已将 onBackPressed 方法添加到 StartGame.java,但它似乎不起作用。
有人对发生的事情有一些线索吗? :/
【问题讨论】:
标签: java android android-studio android-activity onbackpressed