Anton Sobolev
Anton Sobolev

Reputation: 135

Start/stop thread

I can't find any working solution to stopping/resuming a thread when locking/unlocking a device, can anyone help, or tell me where I can find how to do it? I need stop the thread when the phone is locked and start it again when the phone is unlocked.

Upvotes: 2

Views: 14614

Answers (1)

chubbsondubs
chubbsondubs

Reputation: 38676

Java operates on a cooperative interrupt model for stopping threads. That means you can't simply stop a thread mid-execution without cooperation from the thread itself. If you want to stop a thread the client can call Thread.interrupt() method to request the thread stop:

public class SomeBackgroundProcess implements Runnable {

    Thread backgroundThread;

    public void start() {
       if( backgroundThread == null ) {
          backgroundThread = new Thread( this );
          backgroundThread.start();
       }
    }

    public void stop() {
       if( backgroundThread != null ) {
          backgroundThread.interrupt();
       }
    }

    public void run() {
        try {
           Log.i("Thread starting.");
           while( !backgroundThread.interrupted() ) {
              doSomething();
           }
           Log.i("Thread stopping.");
        } catch( InterruptedException ex ) {
           // important you respond to the InterruptedException and stop processing 
           // when its thrown!  Notice this is outside the while loop.
           Log.i("Thread shutting down as it was requested to stop.");
        } finally {
           backgroundThread = null;
        }
    }

The important part of threading is that you don't swallow InterruptedException and instead stop your thread's loop and shutdown because you only get this exception if a client has request the thread interrupt itself.

So you simply need to hook up the SomeBackgroundProcess.start() to the event for unlock, and hook up the SomeBackgroundProcess.stop() to the lock event.

Upvotes: 12

Related Questions