title: How to wait for result of speech recognition in android?
body: <p>I am using recognition listener for speech recognition in android. The basic construct of my class is as follows:</p>
  
  <pre><code>class SpeechInput implements RecognitionListener {
  
      Intent intent;
      SpeechRecognizer sr;
      boolean stop;
  
      public void init() {
          sr = SpeechRecognizer.createSpeechRecognizer(context);
          sr.setRecognitionListener(this);
          intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
          intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
          intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,context.getPackageName());
          intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS,3);
      }
  
      ...
  
  }
  </code></pre>
  
  <p>I am stuck in a situation where I want to run android recognition listener in a loop, something over the lines of:</p>
  
  <pre><code>for(int i=0; i&lt;N; i++) {
         // Some processing code
         sr.startListening(intent);
  }
  </code></pre>
  
  <p>Now, I want to wait for the output before it starts listening again. In order to achieve this, I tried to use locking mechanism as follows:</p>
  
  <pre><code>for(int i=0; i&lt;N; i++) {
         // Some processing code
         sr.startListening(intent);
         stop = false; 
         new Task().execute().get();
  }
  </code></pre>
  
  <p>where Task is an asyncTask defined as follows:</p>
  
  <pre><code>private class Task extends AsyncTask&lt;Void,Void,Void&gt; {
  
          @Override
      protected Void doInBackground(Void... params) {
          try {
              int counter = 0;
              while(!stop) {
                  counter++;
              }
          } catch(Exception e) {
          }
          return null;
      }
  }
  </code></pre>
  
  <p>The boolean value 'stop' is updated in the 'onResults' method of RecognitionListener as follows:</p>
  
  <pre><code>public void onResults(Bundle results) {
      ...
      stop = true;
  }
  </code></pre>
  
  <p>The problem is that speech recognition is not working at all. Nothing is happening, it is not even starting. I guess this is because the asyncTask is taking up all the processor time. Can you please guide me towards an architecture where I would be able to achieve this? Thank you. </p>