我有一个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);
}
我的StartName课程如下:
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中,我通过一个按钮成功地启动了startName的一个新示例(它用和ondraw启动了游戏)。现在,如果用户按下软后退按钮(导航栏),活动将关闭,主活动布局将出现,但我仍然可以听到游戏在后台运行的声音(即使我进入主屏幕),这意味着活动仍在运行。
我已经将onbackpressed方法添加到startgame.java中,但它似乎不起作用。
有人知道发生了什么事吗/
2条答案
按热度按时间yqhsw0fo1#
你开始了一条永远不会停止的线。这个线程也负责音频主题吗?
停止你的线程在onbackpressed也你应该打电话
finish()
在反压中ercv8c1e2#
不知道这是否有效,但试一下,
private UpdateThread myThread
```@Override
public void onBackPressed() {
super.onBackPressed();
myThread.stop(); // don't know 'myThread' has 'stop()' or not
Intent intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);
finish();
}