I new to Android programming and I want to build Time Speaking clock that will speak the current time in every hour.
Please help me with my code, I want it to say the current time in every hour, but It say it in every second, here is my code.
…………………….
……………………………………………………………………………………………
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tts = new TextToSpeech(this, this);
time_textView = findViewById(R.id.time_textView);
hour_textView = findViewById(R.id.hour_textView);
final Handler handler = new Handler();
final Runnable runnable = new Runnable() {
@Override
public void run() {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("h:mm:ss", Locale.getDefault());
String currentTime = simpleDateFormat.format(calendar.getTime());
time_textView.setText(currentTime);
Hour = calendar.getTime().getHours();
Minute = calendar.getTime().getMinutes();
if (Hour == 1 && Minute == 00){
tts.speak("The time is 1 O'clock", TextToSpeech.QUEUE_FLUSH,null);
}
else if (Hour == 2 && Minute == 00){
tts.speak("The time is 2 O'clock", TextToSpeech.QUEUE_FLUSH,null);
}
else if (Hour == 3 && Minute == 00){
tts.speak("The time is 3 O'clock", TextToSpeech.QUEUE_FLUSH,null);
}
else if (Hour == 4 && Minute == 00){
tts.speak("The time is 4 O'clock", TextToSpeech.QUEUE_FLUSH,null);
}
else if (Hour == 5 && Minute == 00){
tts.speak("The time is 5 O'clock", TextToSpeech.QUEUE_FLUSH,null);
}
if (Hour == 6 && Minute == 00){
tts.speak("The time is 6 O'clock", TextToSpeech.QUEUE_FLUSH,null);
}
handler.postDelayed(this, 1000);
}
};
handler.post(runnable);
}
@Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = tts.setLanguage(Locale.US);
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "Language not supported");
} else {
}
} else {
Log.e("TTS", "Initialization Failed!");
}
}
@Override
public void onDestroy() {
// Don't forget to shutdown tts!
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
}
2
Answers
I am afraid you created an infinite loop. You created the
Runnable
and submitted it to the queuehandler.post(runnable);
. Then inside therun()
method you submit it with 1 second delay on withhandler.postDelayed(this, 1000);
.This is why it’s triggered every second. What time does the
time_textView
show?There are better ways how to run scheduled tasks, check on
JobScheduler
for exampleI’m not sure if this is "the right way" to do it, but for the sake of "code sanity" this would be my approach (posting only the modified code):