How to unpause the thread in my Android surfaceview? - android

I actually can pause the thread correctly but when I press the unpause button
it doesn't resume. What am I doing wrong ?
public void pause() {
mRun = false;
while (true) {
try {
_thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
break;
}
_thread = null;
}
public void unpause() {
mRun = true;
_thread = new GameBoardThread(this);
_thread.start();
}

Related

Get Video Play Time android from videoplayer

I write this function to get video time . This functions works fine but when I backpress then it throws exception .
public void videoTimer ()
{
try
{
running = true;
final int duration = mVideoView.getDuration();
thread = new Thread(new Runnable()
{
public void run()
{
do
{
tvVideoTimer.post(new Runnable()
{
public void run()
{
int time = (duration - mVideoView.getCurrentPosition()) / 1000;
tvVideoTimer.setText(getTimeString(mVideoView.getCurrentPosition()));
}
});
try
{
Thread.sleep(500);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
if (!running) break;
}
while (mVideoView.getCurrentPosition() <= duration);
}
});
thread.start();
}
catch (Exception e)
{
e.printStackTrace();
}
}

Unable to kill a Thread in Android

I have created a thread in a class, The code is as follows
private void startThread() {
if (t != null) {
t.interrupt();
}
isFlashOn = true;
t = new Thread() {
public void run() {
try {
try {
SurfaceView surfaceView = (SurfaceView) activity
.findViewById(R.id.surfaceViewCam);
SurfaceHolder surfaceHolder = surfaceView.getHolder();
// surfaceHolder.addCallback(this);
camera.setPreviewDisplay(surfaceHolder);
} catch (Exception e) {
e.printStackTrace();
}
camera.startPreview();
for (int i = seekBarManager.preferenceManager
.get_duration(); i > 0 && !this.isInterrupted(); i--) {
isFlashOn = true;
setBlinkToggle();
sleep(seekBarManager.preferenceManager.get_delay());
if(isFlashOn==false){
break;
}
}
if (camera != null) {
camera.stopPreview();
camera.release();
camera = null;
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
t.start();
}
I stop the thread in a method
private void stopThread() {
if (t != null) {
t.interrupt();
//t.
isFlashOn = false;
}
}
The problem I am facing is, The for loop in the thread seems to be running even after the successful call of Interrupt()
Any help here would be greatly appreciated!
Updated Code
t = new Thread() {
public void run() {
Boolean isStop = false;
try {
try {
SurfaceView surfaceView = (SurfaceView) activity
.findViewById(R.id.surfaceViewCam);
SurfaceHolder surfaceHolder = surfaceView.getHolder();
// surfaceHolder.addCallback(this);
camera.setPreviewDisplay(surfaceHolder);
} catch (Exception e) {
e.printStackTrace();
}
camera.startPreview();
for (int i = seekBarManager.preferenceManager
.get_duration(); i > 0 && !isStop; i--) {
isFlashOn = true;
setBlinkToggle();
sleep(seekBarManager.preferenceManager.get_delay());
}
if (camera != null) {
camera.stopPreview();
camera.release();
camera = null;
}
} catch (Exception e) {
e.printStackTrace();
isStop=true;
//notify();
return;
}
}
};
Purpose of interrupt():
It just sets the interrupted flag to true. After interrupt() has been called the Thread.currentThread().isInterrupted() starts to return false. And that's all.
Another case is if interrupt() is called while the thread is blocked in an invocation of one of the methods that throw InterruptedException, then that method will return throwing the InterruptedException. And if thread's code just "eats" that exception, then the thread will still continue running.
So the correct approach should be to periodically check the interrupted flag. And if interrupted status is detected then just return ASAP. Another common option is not to use Thread.interrupt() at all, but some custom boolean instead.
See the below link for safe stop of thread:-
http://www.java2s.com/Code/Java/Threads/Thesafewaytostopathread.htm

Android game wont start (restart) after hitting back key

i'm having a problem with restarting my game after clicking home or return button on android.
I've found partial solution in thread:
Android crash when app is closed and reopened, but the game after restarting dosen't work properly.
It only shows images/sprites which also moves, but dosen't read touches.
//this is in game view
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) { // ce se spremeni zaslon
}
public void surfaceCreated(SurfaceHolder holder) {
createSprites();
start();
}
public void start() {
loop.setRunning(true);
if (!mGameIsRunning) {
loop.start();
mGameIsRunning = true;
} else {
loop.onResume();
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
boolean retry = true;
while (retry) {
try {
loop.join();
retry = false;
} catch (InterruptedException e) {
}
}
}
//and this is game thread
while (running) {
canvas = null;
try{
canvas = this.surfaceHolder.lockCanvas();
synchronized (surfaceHolder) {
beginTime = System.currentTimeMillis();
framesSkipped = 0;
this.gameView.update();
this.gameView.render(canvas);
synchronized (mPauseLock) {
while (mPaused) {
try {
mPauseLock.wait();
} catch (InterruptedException e) {
}
}
}
timeDiff = System.currentTimeMillis() - beginTime;
sleepTime = (int)(FRAME_PERIOD - timeDiff);
if (sleepTime > 0){
try{
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
}
}
}
} finally {
if (canvas != null){
surfaceHolder.unlockCanvasAndPost(canvas);
}
}
}
}
public void onPause() {
synchronized (mPauseLock) {
mPaused = true;
}
}
public void onResume() {
synchronized (mPauseLock) {
mPaused = false;
mPauseLock.notifyAll();
}
}
Can anyone tell me if there is any mistake or any other solution.
Thanks for help.
Or if anyone could tell me for a good way to stop game and restart it, please?
I fixed it so that it works when i hit home, but when i hit back and restart it, I get black screen.
// current gameview code
public void surfaceCreated(SurfaceHolder holder) {
if (loop==null)
loop = new GameLoop(getHolder(), this);
if(loop.getState() == Thread.State.TERMINATED)
{
loop = new GameLoop(getHolder(), this);
}
start();
}
public void start() {
if (!mGameIsRunning) {
mGameIsRunning = true;
loop.setRunning(true);
loop.start();
} else {
loop.onResume();
loop.start();
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
loop.onPause();
}
I have a feeling that the problem is in surfaceDestroy method, but I'm not sure since I don't know what is the difference between hitting home or back key.

Stop the flashlight after pressing back

I am using a thread to run the flashlight and I want to stop that thread after the back is pressed.
I used the following code to start the thread:
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Flashing...");
progressDialog.show();
thread = new Thread(MainActivity.this);
thread.start();
And the thread is doing:
public void run() {
isOn = false;
cam = Camera.open();
p = cam.getParameters();
try {
for (int i = 0; i < pattern.length; i++) {
if (isOn) {
p.setFlashMode(Parameters.FLASH_MODE_OFF);
cam.setParameters(p);
Thread.sleep(pattern[i]);
isOn = false;
} else {
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
cam.setParameters(p);
Thread.sleep(pattern[i]);
isOn = true;
}
}
}
catch (InterruptedException e) {
e.printStackTrace();
}
cam.release();
handlerFinish.sendEmptyMessage(0);
}
private Handler handlerFinish = new Handler() {
#Override
public void handleMessage(Message msg) {
progressDialog.dismiss();
}
};
I have tried this to stop, but there are only the progress dialog is dismissed but the flashlight is still working:
#Override
public void onBackPressed() {
super.onBackPressed();
p.setFlashMode(Parameters.FLASH_MODE_OFF);
cam.setParameters(p);
isOn = false;
thread.stop();
}
What can I do to achieve my goal (Stop the thread and flashlight after back is pressed)?
try this loop to stop the thread
boolean retry = true;
while (retry) {
try {
thread.join();
retry = false;
} catch (InterruptedException e) {
// try again shutting down the thread
}
}

Android-null pointer exception after onResume in game loop

I am working on an android game.I was the facing the same issue as here
I tried the wait and notify all solution as shown over there.But as soon the app resumes i get Null pointer exception.
Here is the log cat info.
INFO/System.out(8166): on resume
INFO/System.out(8166): !!!! IN THE GAME RESUME ---- >>>
INFO/System.out(8166): SURFACE CREATED
INFO/System.out(8166): thread on resume
INFO/System.out(8166): in thread game pause=true
WARN/dalvikvm(8166): threadid=7: thread exiting with uncaught exception (group=0x4001d800)
ERROR/AndroidRuntime(8166): FATAL EXCEPTION: Thread-11
ERROR/AndroidRuntime(8166): java.lang.NullPointerException
ERROR/AndroidRuntime(8166): at com.org.GummyBlast.GameView.onDraw(GameView.java:442)
ERROR/AndroidRuntime(8166): at com.org.GummyBlast.GameLoopThread.run(GameLoopThread.java:88)
The code inside onSurfaceCreated and onSurfaceDestroyed
private void init() {
gameLoopThread = new GameLoopThread(this);
holder = getHolder();
holder.addCallback(new SurfaceHolder.Callback() {
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
System.out.println(" SURFACE DESTROYED");
nullImages();
boolean retry = true;
//gameLoopThread.setRunning(false);
if(!mGameIsRunning){
while (retry) {
try {
gameLoopThread.join();
retry = false;
} catch (InterruptedException e) {
}
}
}
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
System.out.println(" SURFACE CREATED");
Log.d("surface create", "SURFACE CREATED");
/*gameLoopThread.setRunning(true);
gameLoopThread.start();*/
start(holder);
}
public void start(SurfaceHolder holder) {
if (!mGameIsRunning) {
gameLoopThread.setRunning(true);
gameLoopThread.start();
mGameIsRunning = true;
} else {
gameLoopThread.onResume();
}
}
Code in my GameThread class
public class GameLoopThread extends Thread {
static final long FPS = 10;
private GameView view;
public static boolean running = false;
public static boolean run = true;
public static boolean game_pause=true;
private static Object mPauseLock;
private boolean mFinished=false;
long ticksPS = 1000 / FPS;
long startTime;
long sleepTime;
SurfaceHolder holder;
public GameLoopThread(GameView view) {
mPauseLock = new Object();
this.view = view;
}
public GameLoopThread() {
mPauseLock = new Object();
}
public void setRunning(boolean run) {
running = run;
}
#Override
public void run() {
while (running) {
// Do stuff.
System.out.println("in thread game pause="+Boolean.toString(game_pause));
if (game_pause == true) {
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) {
System.out.println("Error in game loop thread "+ e.getMessage());
}
}
else{
synchronized (mPauseLock) {
while (game_pause==false) {
try {
mPauseLock.wait();
} catch (InterruptedException e) {
}
}
}
}
}
}
public void onPause() {
synchronized (mPauseLock) {
game_pause = false;
System.out.println("thread on pause");
}
}
/**
* Call this on resume.
*/
public void onResume() {
synchronized (mPauseLock) {
game_pause = true;
mPauseLock.notifyAll();
System.out.println("thread on resume");
}
}
}
Activity class onPause
#Override
public void onPause() {
super.onPause();
System.out.println(" --- IN GAME PAUSE ---");
gameLoopThread = new GameLoopThread();
gameLoopThread.onPause();
}
how to maintain the state of the game in onResume?
Thanks
Maybe you need to call onResume() on your superclass:
public void onResume() {
super.onResume();
}
Hope this helps you.

Categories

Resources