Reputation: 95
I have a service running on device boot. It checks for some data and send out Notifications. I came across the following.
http://mobile.tutsplus.com/tutorials/android/android-sdk-using-the-text-to-speech-engine/
and I want to send voice notification. I do not need UI part of it. How do I add it in my project?
Upvotes: 0
Views: 1398
Reputation: 327
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);
}
Upvotes: -1
Reputation: 14022
Create class App
and an instance of TextToSpeech
in it:
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();
}
}
Declare App
(above) in your manifest:
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:name="your.application.package.App" >
Send a broadcast
by your service when you want to a BroadcastReceiver
for example this:
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) {
}
}
Upvotes: 1