SurfaceView实现了Runnable - Thread无法启动

时间:2012-03-23 08:07:53

标签: android multithreading surfaceview android-canvas

一直在寻找使用SurfaceView绘制画布的一些教程,但唯一显示的是黑色背景。

public class FighterActivity extends Activity implements OnTouchListener {
    /** Called when the activity is first created. */
    SurfaceController surface;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        surface = new SurfaceController(this);
        surface.setOnTouchListener(this);
        setContentView(surface);
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        surface.pause();
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        surface.resume();
    }

    public class SurfaceController extends SurfaceView implements Runnable{

        Thread thread = null;
        SurfaceHolder holder;

        public SurfaceController(Context context) {
            super(context);
            // TODO Auto-generated constructor stub
            holder = getHolder();
            System.out.println("HERE");
        }

        public void run() {
            // TODO Auto-generated method stub
            System.out.println("Hello World2");
            while(true){
                if(!holder.getSurface().isValid()){
                    System.out.println("NOT VALID");
                    continue;
                }
                System.out.println("VALID!");
                Canvas can = holder.lockCanvas();
                can.drawARGB(255, 150, 150, 0);
                holder.unlockCanvasAndPost(can);
            }
        }

        public void pause(){

        }

        public void resume(){

        }

    }

    public boolean onTouch(View view, MotionEvent me) {
        // TODO Auto-generated method stub
        return false;
    }
}

它到达System.out.println(“HERE”);并打印出来,但没有更多的事情发生,换句话说线程没有开始,因为“Hello World2”没有打印,有什么问题?

感谢您的帮助

1 个答案:

答案 0 :(得分:3)

我假设你正在建立这个:http://android-coding.blogspot.ca/2011/05/drawing-on-surfaceview.html

您会注意到onResumeMySurfaceViewonPauseMySurfaceView(分别在resumepauseSurfaceController)启动实际线程。您也需要在代码中执行此操作,例如:在SurfaceController

protected boolean running = false;

public void resume() {
    running = true;
    thread = new Thread(this);
    thread.start();
}