Java 按下后退键或home键时应用程序停止工作?
我有3个类,扩展线程的GameThread类,扩展活动的Main类,扩展surfaceview的GameView类,实现surfaceHolder.onCallback:Java 按下后退键或home键时应用程序停止工作?,java,android,Java,Android,我有3个类,扩展线程的GameThread类,扩展活动的Main类,扩展surfaceview的GameView类,实现surfaceHolder.onCallback: public class Main extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.i("oncreate","
public class Main extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i("oncreate","ONcreate");
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.gameloopxml);
}
@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;
}
}
类游戏线程:
public class GameThread extends Thread {
GameView gameview;
SurfaceHolder surfaceHolder;
public boolean running;
public GameThread(SurfaceHolder surfaceHolder,GameView gameview){
this.gameview=gameview;
running=false;
this.surfaceHolder=surfaceHolder;
}
@Override
public void run() {
Canvas c;
//super.run();
while(running){
c=null;
try{
c=surfaceHolder.lockCanvas();
synchronized (surfaceHolder) {
if(c!=null){
c.drawColor(Color.BLACK);
gameview.draw(c);
gameview.update();
}
}
}finally{
if(c!=null){
surfaceHolder.unlockCanvasAndPost(c);
}
}
}
}
}
类游戏视图:
public class GameView extends SurfaceView implements SurfaceHolder.Callback{
GameThread gamethread;
Paint p=new Paint();
int x,y;
Bitmap bitmap;
public GameView(Context context, AttributeSet attrs) {
super(context, attrs);
Log.i("surface", "constructor");
bitmap=BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
//super(context);
p.setColor(Color.RED);
//add the callback this in order to intercept events
getHolder().addCallback(this);
//create the gameloop
//make it foccusable so it can handle events
setFocusable(true);
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
Log.i("surface", "changed");
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
Log.i("surface", "created");
gamethread=new GameThread(getHolder(),this);
gamethread.running=true;
gamethread.start();
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
Log.i("surface", "destroyed");
boolean tryagain=false;
while(tryagain){
try {
gamethread.join();//destroy the thread
tryagain=false;
gamethread.running=false;
} catch (InterruptedException e) {
//try again shutting down the thread
}
}
}
public void draw(Canvas c) {
c.drawRect(x, y, x+80, y+80, p);
}
public void update(){
x++;
y++;
}
}
在我的代码中,除了每次按下back或home键时,我都会在logcat中收到一个Nullpointer异常。您能发布logcat stacktrace吗?空指针发生在哪里?我怀疑当你的活动被破坏时,你没有正确地关闭你的线程。无论如何,我通过停止线程在onPaused方法中运行来解决这个问题