我遇到以下简单代码的问题。我创建了SurfaceView类,它扩展了SurfaceView。我在另一个从onCreate方法开始的线程上运行它:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
GraphicView v = new GraphicView( this );
Thread thread = new Thread( v );
thread.start();
setContentView( v );
}
我不知道为什么但是当我关闭我的应用程序时 - 我收到错误。我不在我的平板电脑上使用英文UI,但我认为英文听起来像这样:“应用程序中出现错误”。仅此而已!也许我需要停止线程?我的代码中是否有错误?
public class GraphicView extends SurfaceView implements Runnable {
Activity activity;
SurfaceHolder holder;
Paint paint;
public GraphicView( Activity activity ) {
super( activity );
this.activity = activity;
paint = new Paint();
paint.setColor( Color.YELLOW );
paint.setStyle( Style.FILL );
holder = getHolder();
}
@Override
public boolean onTouchEvent( MotionEvent me ) {
return false;
}
public void run() {
while ( true ) {
if ( !holder.getSurface().isValid() ) {
continue;
}
Canvas c = holder.lockCanvas();
c.drawARGB( 255, 128, 255, 80 );
holder.unlockCanvasAndPost( c );
}
}
}
所以错误是:
10-31 00:02:20.124: W/KeyCharacterMap(278): No keyboard for id 0
10-31 00:02:20.124: W/KeyCharacterMap(278): Using default keymap: /system/usr/keychars/qwerty.kcm.bin
10-31 00:02:21.104: W/dalvikvm(278): threadid=11: thread exiting with uncaught exception (group=0x4001d800)
10-31 00:02:21.124: E/AndroidRuntime(278): FATAL EXCEPTION: Thread-10
10-31 00:02:21.124: E/AndroidRuntime(278): java.lang.NullPointerException
10-31 00:02:21.124: E/AndroidRuntime(278): at com.example.GraphicView.run(GraphicView.java:192)
10-31 00:02:21.124: E/AndroidRuntime(278): at java.lang.Thread.run(Thread.java:1096)
GraphicView.java的第192行:
c.drawARGB( 255, 128, 255, 80 );
答案 0 :(得分:1)
尝试用while(!yourActivity.isFinishing())
替换while(true)也许更好的是你应该在Activity的onPause中打破你的循环并在onResume()中恢复它