如何暂停和恢复sur​​faceView线程线程、sur、faceView

2023-09-12 03:54:12 作者:女性简单文雅气质的

我有一个surfaceView的设置和运行,但是当我恢复它我得到该线程已经启动的错误。请告诉我正确的方式来处理时,应用程序转到后台再回到前台?香港专业教育学院周围的修修补补,并设法让应用程序回来没有崩溃......但surfaceView犯规画anthing了。我的code:

  @覆盖
    公共无效surfaceCreated(SurfaceHolder持有者){
           Log.e(SYS,surfaceCreated被调用。);
           如果(systemState ==背景){
                  thread.setRunning(真正的);

           }
           其他 {
        thread.setRunning(真正的);
               thread.start();
               Log.e(SYS,启动线程);
               systemState =待用;
           }



    }
    @覆盖
    公共无效surfaceDestroyed(SurfaceHolder持有者){
           Log.e(SYS,surfaceDestroyed被调用。);
           thread.setRunning(假);
           systemState =背景;
    }
 

解决方案

最简单的解决方案是简单地杀死并重新启动线程。创建方法恢复() - 创建线程对象,并启动它 - 暂停() - 杀死线程(见Lunarlander例子) - 在你的SurfaceView类,并调用这些从surfaceCreated和surfaceDestroyed启动和停止线程

现在在运行的SurfaceView的活动,你还需要调用resume()和pause()从活动的(或片段的)onResume(),并在onPause()中的SurfaceView方法。这不是一个完美的解决方案,但它会工作。

I have a surfaceView setup and running, but when i resume it i get an error that the thread has already been started. Whats the proper way to handle when the app goes to the background and then back to the foreground? Ive tinkered around and managed to get the app to come back without crashing...but the surfaceView doesnt draw anthing anymore. My code:

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
           Log.e("sys","surfaceCreated was called.");
           if(systemState==BACKGROUND){
                  thread.setRunning(true);

           }
           else {
        thread.setRunning(true);
               thread.start();
               Log.e("sys","started thread");
               systemState=READY;
           }



    }
    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
           Log.e("sys","surfaceDestroyed was called.");
           thread.setRunning(false);
           systemState=BACKGROUND;
    }

解决方案

The easy solution is to simply kill and restart the thread. Create methods resume() - creates thread object and starts it - and pause() - kills thread (see Lunarlander example) - in your SurfaceView class and call these from surfaceCreated and surfaceDestroyed to start and stop the thread.

Now in the Activity that runs the SurfaceView, you will also need to call the resume() and pause() methods in the SurfaceView from the Activity's (or fragment's) onResume() and onPause(). It's not an elegant solution, but it will work.