How to correctly launch Voice Recognition activity from an activity with singleInstance launch mode?

1.2k Views Asked by At

Already saw another thread which mentions that an activity with RecognizerIntent was not working correctly if launched from within an activity with singleInstance launch mode. So I would like to know what my alternatives are.

My use case is as follows: My application listens for an event, and when this event occurs, it displays an alert dialog, even if the user is in the midst of using another application. From other questions I found that the common way of doing this is to launch an activity with singleInstance launch mode. But now once this alert dialog pops up, I need to use RecognizerIntent and do some speech to text processing. However speech input dialog just does not wait for any input and onActivityResult() is called immediately. Things work fine if my alert dialog pops up from an activity which has a launch mode other than "singleInstance".

Are there other ways to approach this problem ?

1

There are 1 best solutions below

0
On

Try running your Code this way :-

List<ResolveInfo> activities = pm.queryIntentActivities(
            new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
    if (activities.size() != 0) {
        speakButton.setOnClickListener(this);
    } else {
        speakButton.setEnabled(false);
        speakButton.setText("Recognizer not present");
   }

Above code should be written inside onCreate() while below should be written ouside it

public void onClick(View v) {
    if (v.getId() == R.id.btn_speak) {
        startVoiceRecognitionActivity();
    }
}


 private void startVoiceRecognitionActivity() {
    Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
    intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
            RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
    intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speech recognition demo");
    startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);

//Run a loop checking whether the list is empty or not:-
    while(activities.isEmpty()){
        //wait    
    }
//Now run your alert dialog box 
}

I have tested it on DellXCD35 android 2.3.3 and it works perfectly well once you get list of texts in your list view it upto you whihch you want to select.