在Using the Android RecognizerIntent with a bluetooth 耳机中使用我的答案
在您声明 private void speak(String s) 的活动中添加一个类成员
BluetoothHeadsetUtils mBluetoothHelper;
TelephonyManager mTelManager;
MyPhoneStateListener mPhoneStateListener = new MyPhoneStateListener();
在同一活动 onCreate() 添加
@Override
public void onCreate()
{
mBluetoothHelper = new BluetoothHeadsetUtils(this);
mTelManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
mTelManager.listen(mPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
}
并添加活动的 onResume() 和 onPause
@Override
onResume()
{
mBluetoothHelper.start();
}
@Override
onPause()
{
mBluetoothHelper.stop();
}
您可以将您的 speak(String s) 定义为
public void speak(String s, String utteranceId) // utteranceId can be an empty string
{
HashMap<String, String> myHashRender = new HashMap<String, String>();
myHashRender.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, utteranceId);
if (mBluetoothHelper.isOnHeadsetSco())
{
myHashRender.put(TextToSpeech.Engine.KEY_PARAM_STREAM,
String.valueOf(AudioManager.STREAM_VOICE_CALL));
}
tts.speak(s, TextToSpeech.QUEUE_ADD, myHashRender);
}
而不是广播接收器使用电话状态监听器
protected class MyPhoneStateListener extends PhoneStateListener
{
@Override
public void onCallStateChanged(int state, String incomingNumber)
{
switch (state)
{
case TelephonyManager.CALL_STATE_RINGING:
mAudioManager.setStreamMute(AudioManager.STREAM_RING, true);
speak("whatever you want here", "ringing"); //$NON-NLS-1$
Log.d(TAG, "ringing cancel recognizer"); //$NON-NLS-1$
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
Log.d(TAG, "offhook cancel recognizer"); //$NON-NLS-1$
break;
case TelephonyManager.CALL_STATE_IDLE:
new Thread(new Runnable()
{
@Override
public void run()
{
try
{
Thread.sleep(2000);
}
catch (InterruptedException e)
{
}
mBluetoothHelper.start();
}
}).start();
Log.d(TAG, "call state idle"); //$NON-NLS-1$
}
}
}
在您的活动或服务中添加实现 OnUtteranceCompletedListener 并添加以下代码
@Override
public void onUtteranceCompleted(String utteranceId)
{
if (utteranceId.equals("ringing"))
{
mAudioManager.setStreamMute(AudioManager.STREAM_RING, false);
mBluetoothHelper.stop();
}
}