how to use toggle switch by result of speech recognition

会有一股神秘感。 提交于 2019-12-12 05:24:17

问题


i want use toggle switch by voice commands like switch on and switch off so i got a code for voice recognition from a site but dont know how to trigger my toggle button thru it

The code of voice recognition i used -

package com.authorwjf.talk2me;

import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {

protected static final int REQUEST_OK = 1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    findViewById(R.id.button1).setOnClickListener(this);
}

@Override
public void onClick(View v) {
     Intent i = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
     i.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-US");
     try {
         startActivityForResult(i, REQUEST_OK);
     } catch (Exception e) {
         Toast.makeText(this, "Error initializing speech to text engine.", Toast.LENGTH_LONG).show();
     }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode==REQUEST_OK  && resultCode==RESULT_OK) {
        ArrayList<String> thingsYouSaid = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
        ((TextView)findViewById(R.id.text1)).setText(thingsYouSaid.get(0));



    }
}

}


回答1:


your array thingsYouSaid have all possible string array you have . for example if I say hello it will have like [hello,aloe,hallo,no] so what you have to do is you can match your string switch off to result string array and if it is match with like "switch off" than change value of your switch from on to off likewise;

    if (requestCode==REQUEST_OK  && resultCode==RESULT_OK) {
            ArrayList<String> thingsYouSaid = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);

    for(String value : thingsYouSaid.get(0)){

    if(value.equalsignorecase("switch off")){
      // change value for switch to off

       break;
    }
    else if(value.equalsignorecase("switch on")){
    // change value for switch to on
    break;
    }


 }


来源:https://stackoverflow.com/questions/35461826/how-to-use-toggle-switch-by-result-of-speech-recognition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!