Search code examples
androidvoicevoice-recognition

How to open Activity based on the voice command


I am doing dashboard application in which there are lot of screens. When the user tell the voice command based on that I need to open the activity. I don't know where to start I have already completed all the screens and I would like to implement voice search. my app screens are Advances, Leaves, Recruitment, Permissions, Notifications etc Example: when the user say 'Advances' it should open the advances screens. Please help me.


Solution

  • 1) Start a voice recognition intent

    2) Handle the returned data in onActivityResult() to decide which activity to start

    1. Start a voice recognition intent

    Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
    intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
    intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Choose Activity");
    startActivityForResult(intent, REQUEST_SPEECH);
    

    2. Handle the returned data

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data){
            if (requestCode == REQUEST_SPEECH){
                if (resultCode == RESULT_OK){
                    ArrayList<String> matches = data
                        .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
    
                    if (matches.size() == 0) {
                        // didn't hear anything
                    } else {
                        String mostLikelyThingHeard = matches.get(0);
                        // toUpperCase() used to make string comparison equal
                        if(mostLikelyThingHeard.toUpperCase().equals("ADVANCES")){
                            startActivity(new Intent(this, Advances.class));
                        } else if() {
                        }
                    }
                }
            }
    
            super.onActivityResult(requestCode, resultCode, data);
        }