我在设备引导上运行了一个服务。它检查一些数据并发送通知。我偶然发现了以下情况。
http://mobile.tutsplus.com/tutorials/android/android-sdk-using-the-text-to-speech-engine/
我想发送语音通知。我不需要UI的一部分。如何将它添加到我的项目中?
发布于 2012-08-24 15:46:12
创建类App及其中的TextToSpeech实例:
public class App extends Application {
private static TextToSpeech mTts;
public static TextToSpeech getmTts() {
return mTts;
}
public void onCreate() {
super.onCreate();
// creating TTS:
mTts = new TextToSpeech(this, this);
mTts.setLanguage(Locale.US);
mTts.stop();
}
} 在您的清单中声明App(上面):
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:name="your.application.package.App" >当您想要发送到一个broadcast时,通过服务发送一个BroadcastReceiver,例如:
public class TTSReceiver extends BroadcastReceiver implements OnInitListener {
private TextToSpeech mTts;
private String message;
@Override
public void onReceive(Context context, Intent intent) {
mTts = App.getmTts();
mTts.setLanguage(Locale.US);
message = "your message";
mTts.stop();
mTts.speak(message, TextToSpeech.QUEUE_FLUSH, null);
}
public void onInit(int status) {
}
}发布于 2013-03-19 17:27:36
public class SpeakService extends Service implements OnInitListener {
public static TextToSpeech tts;
private String string;
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public void onCreate() {
tts = new TextToSpeech(this, this);
super.onCreate();
}
@Override
public void onDestroy() {
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
string = intent.getStringExtra("string");
}
@Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = tts.setLanguage(Locale.UK);
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.d("SpeakService", "Language is not available.");
} else {
if (!TextUtils.isEmpty(string)) {
speak(string);
} else {
speak("Error");
}
}
} else {
Log.d("SpeakService", "Could not initialize TextToSpeech.");
}
}
private void speak(String string) {
tts.speak(string, TextToSpeech.QUEUE_FLUSH, null);
}https://stackoverflow.com/questions/12111209
复制相似问题