我有一个SurfaceView和GameThread类。GameThread一直在SurfaceView类上更新和绘制。
现在,当我退出应用程序(通过按下Home或Back按钮)时,我会收到一个强制关闭应用程序的消息。这是因为GameThread仍然试图在已擦除的SurfaceView上绘制...
那么,我如何正确地结束应用程序而不会收到此强制关闭通知?我希望在按下后退按钮时GameThread类停止。在按下Home并在后台运行时,它应该暂停。重新进入仍在运行的游戏时,它应该恢复...
有什么想法吗?
这是我的Gamethread类:
它不断更新我的GameView类:
公共类GameView扩展SurfaceView{
现在,当我退出应用程序(通过按下Home或Back按钮)时,我会收到一个强制关闭应用程序的消息。这是因为GameThread仍然试图在已擦除的SurfaceView上绘制...
那么,我如何正确地结束应用程序而不会收到此强制关闭通知?我希望在按下后退按钮时GameThread类停止。在按下Home并在后台运行时,它应该暂停。重新进入仍在运行的游戏时,它应该恢复...
有什么想法吗?
这是我的Gamethread类:
public class GameThread extends Thread{
private GameView view;
public boolean isRunning = false;
public GameThread(GameView view) {
this.view = view;
}
public void setRunning(boolean setRunning) {
isRunning = setRunning;
}
public void run() {
while(isRunning) {
Canvas c = null;
view.update();
try {
c = view.getHolder().lockCanvas();
synchronized (view.getHolder()) {
view.draw(c);
}
}finally {
if(c != null) {
view.getHolder().unlockCanvasAndPost(c);
}
}
}
}
它不断更新我的GameView类:
公共类GameView扩展SurfaceView{
private GameThread gameThread;
public GameView(Context context, Activity activity) {
super(context);
gameThread = new GameThread(this);
init();
holder = getHolder();
holder.addCallback(new SurfaceHolder.Callback() {
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
gameThread.setRunning(true);
gameThread.start();
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
}
});
}
public void init() {
}
public void update() {
}
public void draw(Canvas canvas) {
super.draw(canvas);
}
}
当按下Home键时,我的Logcat会显示如下信息:
02-24 18:24:59.336: E/SurfaceHolder(839): Exception locking surface
02-24 18:24:59.336: E/SurfaceHolder(839): java.lang.IllegalStateException: Surface has already been released.
02-24 18:24:59.336: E/SurfaceHolder(839): at android.view.Surface.checkNotReleasedLocked(Surface.java:437)
02-24 18:24:59.336: E/SurfaceHolder(839): at android.view.Surface.lockCanvas(Surface.java:245)
02-24 18:24:59.336: E/SurfaceHolder(839): at android.view.SurfaceView$4.internalLockCanvas(SurfaceView.java:872)
主要活动:
public class MainActivity extends Activity {
private RelativeLayout relativeLayout;
private GameView gameView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
gameView = new GameView(this, this);
setContentView(R.layout.activity_main);
relativeLayout = (RelativeLayout)findViewById(R.id.mainView);
relativeLayout.addView(gameView);
}
@Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
gameView.onBackPressed();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}