断开语音识别服务



如果我像这样使用语音识别

Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);

做一些设置....并使

startActivityForResult(intent, SystemData.VOICE_RECOGNITION_REQUEST_CODE);

是否有一种方法来停止服务(如销毁)使用一些意图或任何其他方式?

谢谢酒吧。

我找到了如何停止语音识别服务。我创建了一个类型为SpeechRecognizer的通用变量。

把它放在课的开头,像这样:

private speech = null;

然后在speech初始化中,我将它连接到一个听者,并在intent中像这样使用它:

    speech = SpeechRecognizer.createSpeechRecognizer(getActivity());
    speech.setRecognitionListener(this);
    Intent recognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);

然后在这堂课的任何部分如果我想激活演讲,我使用这个:

speech.startListening (recognizerIntent);

,我这样做来停止它:

speech.stopListening ();

所以听者是言语活动的关键。

首先在activity xml中添加两个按钮[buttonStart和buttonStop],然后
在包含问题代码的活动中添加:@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate (savedInstanceState);setContentView (R.layout.main);

    buttonStart = (Button) findViewById(R.id.buttonStart);
    buttonStop = (Button) findViewById(R.id.buttonStop);
    buttonStart.setOnClickListener(this);
    buttonStop.setOnClickListener(this);
  }
  public void onClick(View src) {
    switch (src.getId()) {
    case R.id.buttonStart:
      Log.d(TAG, "onClick: starting srvice");
      startService(new Intent(this, MyService.class));
      break;
    case R.id.buttonStop:
      Log.d(TAG, "onClick: stopping srvice");
      stopService(new Intent(this, MyService.class));
      break;
    }
  }

MyService.java

mport android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class MyService extends Service {
    private static final String TAG = "MyService";
    MediaPlayer player;
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    @Override
    public void onCreate() {
        Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
        Log.d(TAG, "onCreate");
        player = MediaPlayer.create(this, R.raw.braincandy);
        player.setLooping(false); // Set looping
    }
    @Override
    public void onDestroy() {
        Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
        Log.d(TAG, "onDestroy");
        player.stop();
    }
    @Override
    public void onStart(Intent intent, int startid) {
        Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
        Log.d(TAG, "onStart");
        player.start();
    }
}

最新更新