Android: `RecognizerIntent.EXTRA_MAX_RESULTS` does not limit the number of results

I am using Android SpeechRecognizer and want to limit the number of transcription results returned by Google.

From the EXTRA_MAX_RESULTS documentation in RecognizerIntent it looks like I want:

An additional limit on the maximum number of returned results. If you skip, the recognizer will choose how many results will be returned. Must be an integer.

However, adding this addition to the intent has no effect. Bundle onResults Bundle always has five transcriptions, no matter what number I specify.

 public class MainActivity extends AppCompatActivity implements RecognitionListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final SpeechRecognizer recognizer = SpeechRecognizer.createSpeechRecognizer(getApplicationContext()); recognizer.setRecognitionListener(this); final Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM); intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 2); //should limit to 2 results FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { recognizer.startListening(intent); } }); } @Override public void onResults(Bundle results) { ArrayList<String> matches = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION); if (matches != null && !matches.isEmpty()) { Log.d("All matches", "number matches: " + matches.size()); //always 5 } } ... } 

What is the correct way to limit the number of transcriptions that Google returns?

+6
source share
1 answer

You must use RecognizerIntent with startActivityForResult(intent, REQ_CODE_SPEECH_RESULT);

Like this:

 fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { startActivityForResult(intent, REQ_CODE_SPEECH_RESULT); } }); @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case REQ_CODE_SPEECH_RESULT: { if (resultCode == RESULT_OK && null != data) { ArrayList<String> result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS); } break; } } } 

Extract from RecognizerIntent documentation:

Launches an action that will ask the user for speech and send it through the speech recognizer. The results will be returned through the activity results (in Activity.onActivityResult ) if you start the intent using Activity.startActivityForResult(Intent, int) , or redirected through the PendingIntent if provided.

0
source

Source: https://habr.com/ru/post/1238558/


All Articles