简体   繁体   中英

Pausing and Resuming android thread in stateView class

I'm currently implementing an android game and faced a problem in pausing and resuming the thread. Here is the `package com.andromeda.bubbleshooter;

import android.graphics.Canvas; import android.view.SurfaceHolder;

public class MainThread extends Thread {

// flag to hold game state
private boolean running;
public static boolean stop;

private SurfaceHolder surfaceHolder;
public GameLoop gamePanel;

public MainThread(SurfaceHolder surfaceHolder, GameLoop gamePanel) {
    super();
    this.surfaceHolder = surfaceHolder;
    this.gamePanel = gamePanel;
}

public void setRunning(boolean running) {
    this.running = running;
}

@Override
public void run() {
    Canvas canvas = null;
    while (running) {

        // update game state
        // render state to the screen
        try {
            canvas = this.surfaceHolder.lockCanvas();
            synchronized (surfaceHolder) {
                // if (running)
                gamePanel.draw(canvas);
            }
        } finally {
            // in case of an exception the surface is not left in
            // an inconsistent state
            if (canvas != null) {
                surfaceHolder.unlockCanvasAndPost(canvas);
            }
        } // end finally

    }
}

} `

In the Game loop class which extends surfaceView, I'm initializing the thread in the constructor, when clicking on the pause button I invoke .setRunning(false), and when resuming I invoke .setRunning(true). When pausing the game its ok, but when clicking back the button to resume, nothing changes and game is freezed.

This is because when you set isRunning to false in pause, you exit the while loop and leave the run function, which causes the thread to end. Rather than setting isRunning, you should provide some other form of synchronization. One wasy way would be to have a semaphore with a single ticket. You could take it in pause() and release it in resume(), and take it then release it at the beginning of each run through the main thread loop. That way if you're paused you'll wait for the semaphore to be released before running again.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM