我遇到了问题
点击主页按钮时,我的游戏线程类暂停了。但是当重新进入应用程序并且onResume()方法被调用时,它应该恢复游戏线程......我得到的就是力量关闭。
这是我的MainActivity:
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
protected void onPause() {
super.onPause();
gameView.pause();
}
@Override
protected void onResume() {
super.onResume();
if(gameView.getGameThread() != null) {
if(gameView.getGameThread().isRunning == false) {
gameView.resume();
}
}
}
}
gameView是关注类,一个由GameThread渲染的surfaceView:
public class GameView extends SurfaceView{
private GameThread gameThread;
public GameView(Context context, Activity activity) {
super(context);
gameThread = new GameThread(this);
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 GameThread getGameThread() {
return gameThread;
}
public void update() {
}
public void pause() {
gameThread.pause();
}
public void resume() {
gameThread.resumeThread();
}
}
这是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 stopThread() {
isRunning = false;
}
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);
}
}
}
}
public void startThread() {
isRunning = true;
}
public void pause() {
isRunning = false;
}
public void resumeThread() {
isRunning = true;
}
}
我删除了代码中不相关的部分。
当重新进入应用程序时,android.view.Choreographer类打开
有什么想法吗?
答案 0 :(得分:1)
实际上你并没有暂停你的线程(严格来说,没有暂停线程的事情)。你结束了你的主题。
当您调用pause()时,将isRunning
标志设置为false,这会使线程退出循环并且线程结束。当你再次将'isRunning'设置为true时,线程将不会重新启动。
实际上你不能在java中重用线程,你必须创建一个新线程,因为一旦线程循环结束,它就死了。