0

我对以下简单代码有疑问。我创建了扩展 SurfaceView 的 GraphicView 类。我在另一个从 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 );
4

1 回答 1

1

尝试用 while(!yourActivity.isFinishing()) 替换 while(true)

也许更好的是,您应该在 Activity 的 onPause 中打破循环并在 onResume() 中恢复它

于 2012-10-30T20:05:08.863 回答