当我推动家庭'按钮,我的应用程序被杀死

时间:2014-06-08 14:58:05

标签: java android multithreading surfaceview

这是我的代码:

public class Play extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new MainSurfaceView(this));
}

@Override
protected void onPause() {
super.onPause();

}

public class MainSurfaceView extends SurfaceView implements
SurfaceHolder.Callback {

private SurfaceHolder mSurfaceHolder;
private DrawingThread mThread;

private Bitmap background;

public MainSurfaceView(Context context) {
super(context);

mSurfaceHolder = getHolder();
mSurfaceHolder.addCallback(this);
mThread = new DrawingThread();

background = BitmapFactory.decodeResource(getResources(),
R.drawable.background);
}

@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {

}

@Override
public void surfaceCreated(SurfaceHolder holder) {
mThread.keepRunning = true;
mThread.start();
}

@Override
public void surfaceDestroyed(SurfaceHolder holder) {
mThread.keepRunning = false;
boolean retry = true;
while (retry) {
try {
mThread.join();
retry = false;
} catch (InterruptedException e) {
}
}
}

private class DrawingThread extends Thread {
boolean keepRunning = true;

@Override
public void run() {
Canvas c;
while (keepRunning) {
c = null;

try {
c = mSurfaceHolder.lockCanvas();
synchronized (mSurfaceHolder) {
c.drawBitmap(background, 0, 0, null);
}
} finally {
if (c != null)
mSurfaceHolder.unlockCanvasAndPost(c);
}

try {
Thread.sleep(1);
} catch (InterruptedException e) {
}
}
}
}

}
}

错误日志:

  06-08 02:42:54.992: W/dalvikvm(10721): threadid=12: thread exiting with uncaught exception (group=0x4154bba8)
  06-08 02:42:54.992: E/AndroidRuntime(10721): FATAL EXCEPTION: Thread-478
  06-08 02:42:54.992: E/AndroidRuntime(10721): Process: com.yong.space, PID: 10721
  06-08 02:42:54.992: E/AndroidRuntime(10721): java.lang.NullPointerException
  06-08 02:42:54.992: E/AndroidRuntime(10721): at com.yong.space.Play$MainSurfaceView$DrawingThread.run(Play.java:81)

1 个答案:

答案 0 :(得分:0)

当你没有拥有屏幕时,我的赌注就是lockCanvas失败,并返回null。你应该进行空检查,并且可能要么在你接到onPause电话时杀死线程或暂停它 - 否则你会忙着循环并烧掉试图画画但却失败的周期。