Android整点报时语音时钟开发求助:代码每秒重复播报问题
问题修正方案
你的代码会每秒重复播报的核心原因是:Runnable每秒执行一次,整点时段(比如1:00:00到1:00:59)的每一秒都满足Hour == X && Minute == 0的判断条件,导致每秒都触发播报。下面是修正后的代码,同时优化了冗余的判断逻辑:
public class MainActivity extends AppCompatActivity implements TextToSpeech.OnInitListener { private TextToSpeech tts; private TextView time_textView, hour_textView; // 记录上一次播报的小时,避免同一整点重复播报 private int lastAnnouncedHour = -1; /** 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(Looper.getMainLooper()); 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); int currentHour = calendar.get(Calendar.HOUR); // 12小时制,用HOUR_OF_DAY可切换为24小时制 int currentMinute = calendar.get(Calendar.MINUTE); int currentSecond = calendar.get(Calendar.SECOND); // 仅在整点的第0秒触发播报,且确保同一小时只播报一次 if (currentMinute == 0 && currentSecond == 0 && currentHour != lastAnnouncedHour) { // 动态生成播报文本,替代冗余的else if判断 String announceText = String.format("The time is %d O'clock", currentHour); tts.speak(announceText, TextToSpeech.QUEUE_FLUSH, null); // 更新已播报的小时标记 lastAnnouncedHour = currentHour; } 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 { Log.e("TTS", "Initialization Failed!"); } } @Override public void onDestroy() { if (tts != null) { tts.stop(); tts.shutdown(); } super.onDestroy(); } }
关键修改说明:
- 新增
lastAnnouncedHour成员变量,标记已播报的小时,避免同一整点重复触发 - 收紧播报条件:只有当分钟、秒都为0且当前小时未播报过时,才执行语音播报
- 用动态字符串拼接替代大量
else if,简化代码结构 - 修正了Calendar时间获取的写法,改用
calendar.get()方法替代过时的getTime().getHours()
内容的提问来源于stack exchange,提问作者Michelle
相关产品推荐
相关产品推荐

