masmic
masmic

Reputation: 3574

Start a thread inside another thread

INTRODUCTION

I have a sub-class inside my main activity's class, which extends thread and is started every time the camera detectecs movement.

Inside this thread, when it dectects movement continuosly, it must start another thread which belongs to the main Activity's class.

I now it can be a bit messy but i'l explain it now in detail

CODE

This is a simplified version of my code that shows exactly what I mean:

public class MainActivity extends Activity {

    //...

    public Runnable SpeechWhenMotion = new Runnable() {
        @Override
        public void run() {

        // Do stuff here

        }
    }

    private static final class DetectionThread extends Thread {

    //...

    @Override
        public void run() {

        //...
        //START "SpeechWhenMotion" HERE! 

        }
    }
}

QUESTION

So the doubt I have is, how do I start the Runnable inside the thread of the DetectionThread class? I've tryed using a handler but I think I'm not doing it right cause it doesn't get started.

Upvotes: 0

Views: 1896

Answers (2)

Alexander Semenov
Alexander Semenov

Reputation: 1551

If you really need SpeechWhenMotion runnable to be nester class of MainActivity you need to provide link of MainActivity or SpeechWhenMotion instance to DetectionThread class:

 private static final class DetectionThread extends Thread {

    private Runnable mSpeechWhenMotionRunnable;

    //...
 }

then, when you create DetectionThread assign SpeechWhenMotion to it from main activity

DetectionThread detectionThread = new DetectionThread();
detectionThread.mSpeechWhenMotionRunnable = SpeechWhenMotion;

And finally, call start new thread inside DetectionThread:

   //START "SpeechWhenMotion" HERE! 
   new Thread(mSpeechWhenMotionRunnable).start();

Upvotes: 2

KlausD
KlausD

Reputation: 11

I tried it out and this works rather smoothly:

new Thread(SpeechWhenMotion).start();

Upvotes: 0

Related Questions