java - Pausing and Resuming android thread in stateView class -
i'm implementing android game , faced problem in pausing , resuming thread. here `package com.andromeda.bubbleshooter;
import android.graphics.canvas; import android.view.surfaceholder;
public class mainthread extends thread {
// flag 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 screen try { canvas = this.surfaceholder.lockcanvas(); synchronized (surfaceholder) { // if (running) gamepanel.draw(canvas); } } { // in case of exception surface not left in // inconsistent state if (canvas != null) { surfaceholder.unlockcanvasandpost(canvas); } } // end } } } `
in game loop class extends surfaceview, i'm initializing thread in constructor, when clicking on pause button invoke .setrunning(false), , when resuming invoke .setrunning(true). when pausing game ok, when clicking button resume, nothing changes , game freezed.
this because when set isrunning false in pause, exit while loop , leave run function, causes thread end. rather setting isrunning, should provide other form of synchronization. 1 wasy way have semaphore single ticket. take in pause() , release in resume(), , take release @ beginning of each run through main thread loop. way if you're paused you'll wait semaphore released before running again.
Comments
Post a Comment