问题描述
- BroadcastReceiver 呼叫服务只循环一次
-
下面是我的 tts 服务代码:public class SMSTTSService extends Service implements TextToSpeech.OnInitListener, OnUtteranceCompletedListener { private TextToSpeech tts; private String spokenText; @Override public void onCreate() { tts = new TextToSpeech(this, this); } @Override public void onInit(int status) { if (status == TextToSpeech.SUCCESS) { int result = tts.setLanguage(Locale.ENGLISH); // tts.setPitch(5); // set pitch level // tts.setSpeechRate(2); // set speech speed rate if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) { Log.e("TTS", "Language is not supported"); } else { speakOut(spokenText); } /*if (result != TextToSpeech.LANG_MISSING_DATA && result != TextToSpeech.LANG_NOT_SUPPORTED) { tts.speak(c, TextToSpeech.QUEUE_FLUSH, null); }*/ } else { Log.e("TTS", "Initilization Failed"); } } private void speakOut(String text) { tts.speak(text, TextToSpeech.QUEUE_FLUSH, null); } @Override public void onUtteranceCompleted(String uttId) { stopSelf(); } @Override public void onDestroy() { if (tts != null) { tts.stop(); tts.shutdown(); } super.onDestroy(); } @Override public IBinder onBind(Intent intent) { return null; } @Override public void onStart(Intent intent, int startId) { super.onStart(intent, startId); spokenText = intent.getStringExtra("spoken_txt"); } }
从接收器中调用服务器:
public class Receiver extends BroadcastReceiver { private static final String TAG = "SMSReceiver"; @Override public void onReceive(Context context, Intent intent) { for(int i=0; i<msgs.length; i++) { .... Intent intentTTS = new Intent(context, SMSTTSService.class); intentTTS.putExtra("spoken_txt", msgBody); context.startService(intentTTS); }
但是在循环语句中服务器只执行一次。这是哪的问题?如何避免?
解决方案
先检查下msgs.length长度
长度没问题,改成这样行不行
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
spokenText = intent.getStringExtra("spoken_txt");
//do your method
speakOut(spokenText);
}
时间: 2025-01-31 01:21:02