我目前正在努力使onStop()和onResume()方法正确。我遇到的问题是,当我通过onResume()方法重新打开应用程序时,每次都会调用我的surfaceCreated()方法。因为游戏在surfaceCreated()方法中初始化,这显然会导致游戏重启。但我的目标是让它继续停止。 我尝试在启动布尔值的情况下停止初始化过程,但这会导致应用程序崩溃,即使它在开始时已初始化。
public class GamePanel extends SurfaceView implements SurfaceHolder.Callback{
public MainThread thread;
private static MainActivity context;
private boolean started = false;
public GamePanel(MainActivity context){
super(context);
this.context = context;
getHolder().addCallback(this);
thread = new MainThread(this.getHolder(), this);
setFocusable(true);
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
if(!started){
DisplayMetrics displayMetrics = new DisplayMetrics();
context.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
thread.start();
}
thread.setRunning(true);
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
try {
thread.setRunning(false);
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
我删除了所有不重要的东西
public class MainActivity extends AppCompatActivity {
private GamePanel gamePanel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
gamePanel = new GamePanel(this);
setContentView(gamePanel);
}
protected void onResume(){
super.onResume();
gamePanel.thread.setRunning(true);
}
protected void onStop(){
super.onStop();
}
protected void onPause(){
super.onPause();
gamePanel.thread.setRunning(false);
}
}
我通过将thread.running设置为false来停止线程。哪个应该暂停应用逻辑,并且只有通过再次将thread.running设置为true来调用onResume()方法时才会继续。 每次重新打开应用程序时,我是否必须重新创建SurfaceView?
我是Android的新手,我无法在网上找到解决方案。 提前谢谢!