Search code examples
androidandroid-widgetandroid-keypad

Is there a way to launch voice input on the softkeyboard programatically?


The idea is to take a user voice input on the press of a button and pass it to the search inside the app. Because of device limitations we are using the SearchViewCompat instead of the useful SearchView. I have been able to grab the voice output using this link, but there is not a simple way to pass the text to the search bar this way.
The search view itself shows as a view (so no setText()), but if I can just say "use mic key on keyboard" or something as soon as the searchbar comes up, I think it might work. Any help would be greatly appreciated.
Thanks, SGB.


Solution

  • Sorry to have answered my own question but here it was: I took the whole "grab a string array from voice input" off of the link in the question, then, instead of just starting a search with onSearchRequested(), I did this:

    startSearch(grabString, false, null, false);
    
    
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(aViaBuildConfig.MIC_KEY) {
            DebugLog.e(TAG , "onDown event : " + event);
            DebugLog.e(TAG , "onDown keyCode: " + keyCode);
            if(keyCode == Constants.MIC_KEY) {
                onSearchRequested();
                Intent voiceIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
                voiceIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
                try {
                    startActivityForResult(voiceIntent, Constants.RESULT_SPEECH);
                } catch (ActivityNotFoundException ex) {
                    DebugLog.e(TAG, "Not found excpetion onKeyDown: " + ex);
                }
            }
            return super.onKeyDown(keyCode, event);
        }
        return false; 
    }
    
    
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case Constants.RESULT_SPEECH:
                super.onActivityResult(requestCode, resultCode, data);
                if (resultCode == RESULT_OK && null != data) {
                     ArrayList<String> spokenSearch = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
                     DebugLog.e("Glenn: " , "Speech = " + spokenSearch);
                     String grabString = spokenSearch.get(0);
                     startSearch(grabString, false, null, false);
                }
                break;
        }
    }