我有3个类,类扩展线程的GameThread,扩展Activity的类Main,扩展surfaceview的类GameView实现surfaceHolder.onCallback:
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;
}
}
类GameThread:
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);
}
}
}
}
}
类GameView:
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++;
}
}
我的代码中的一切都运行良好,只要按下后面或主页键我就会在logcat中获得Nullpointer异常。