1

I know this question was asked so many times before. I don't want to add a flag in the Run() method. because the method still runs and drains battery. How can I stop the Thread completely?!

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_layout);

    AudioDispatcher dispatcher = AudioDispatcherFactory.fromDefaultMicrophone(22050,1024,0);
    dispatcher.addAudioProcessor(new PitchProcessor(PitchEstimationAlgorithm.AMDF, 22050, 1024, new PitchDetectionHandler() {

        @Override
        public void handlePitch(PitchDetectionResult pitchDetectionResult,
                AudioEvent audioEvent) {
            final float pitchInHz = pitchDetectionResult.getPitch();
            runOnUiThread(new Runnable() {
                 @Override
                 public void run() {

                    Log.i("" + pitchInHz);

                }
            });

        }
    }));

    Thread thread = new Thread(dispatcher,"Audio Dispatcher");
    thread.start();

}
Mandrake
  • 115
  • 6
  • 1
    Using a flag or interrupt are the only clean ways of doing it. If your thread keeps running for too long, then adjust your code to check for the flag in more places. But trying to abort a thread using some form of brute force mechanism will lead to bigger problems than a bit of battery drainage. – sstan Jul 10 '15 at 18:10
  • please, see: http://stackoverflow.com/questions/3194545/how-to-stop-a-java-thread-gracefully?rq=1 – melli-182 Jul 10 '15 at 18:25
  • @sstan how can I stop the audio process in my code? Should I stop the thread? – Mandrake Jul 10 '15 at 19:29

2 Answers2

1

Pretty sure it doesnt matter to you anymore but for anyone who might use TarsosDSP in the future and faces the same problem then the easiest way is to make a global dispatcher

dispatcher = AudioDispatcherFactory.fromDefaultMicrophone(22050,1024,0);

And simply stop the Thread with this:

dispatcher.stop();
Richard
  • 1,087
  • 18
  • 52
  • Does this also stop the Thread in which the dispatcher object was passed as an argument? – sri Jul 10 '18 at 16:53
0
Thread myThread =....
myThread.stop();

disclaimer: this method is deprecated so I might be weary of using it, but it is indeed a brute way to stop a thread. Other than that, using a volatile flag is my only thought.

Note that using the myThread.stop() method will immediately throw a ThreadDeath exception which must be caught. It will also result in the release of all locks a thread has required.

Edit: you may also be able to call Thread.interrupt() from your main method to set an internal interrupt status flag. (The thread will poll that flag using Thread.interrupted() which will return true if the thread has been interrupted and cleared the status flag

GregH
  • 5,125
  • 8
  • 55
  • 109