how to pause and resume a surfaceView thread

前端 未结 8 1277
野趣味
野趣味 2020-12-02 08:21

I have a surfaceView setup and running, but when I resume it I get an error that the thread has already been started. What\'s the proper way to handle when the app goes to t

8条回答
  •  被撕碎了的回忆
    2020-12-02 08:42

    This is what I have used. The app does not crashes now.

    View Class:

    holder.addCallback(new Callback() {
    
            public void surfaceDestroyed(SurfaceHolder holder) {
                gameLoopThread.setRunning(false);
                gameLoopThread.stop();
            }
    
            public void surfaceCreated(SurfaceHolder holder) {
                gameLoopThread.setRunning(true);
                gameLoopThread.start();
    
            }
    

    In the GameLoopThread :

    private boolean running = false;
    
    public void setRunning(boolean run) {
        running = run;
    }
    @Override
    public void run() {
        long ticksPs=1000/FPS;
        long startTime;
        long sleepTime;
    
    while(running){
            Canvas c = null;
            startTime=System.currentTimeMillis();
            try {
                c = view.getHolder().lockCanvas();
                synchronized (view.getHolder()) {
    
                    view.onDraw(c);
    
                }
    
            } finally {
    
                if (c != null) {
                    view.getHolder().unlockCanvasAndPost(c);
                }
    
            }
            sleepTime=ticksPs-(System.currentTimeMillis()-startTime);
            try{
    
                if(sleepTime>0){
                    sleep(sleepTime);
                }
                else
                    sleep(10);
            } catch(Exception e){}
    }
    
    }
    

    I hope it will help.

提交回复
热议问题