"class ReportLocationHandler extends Handler {\n\n\t\t@Override\n\t\tpublic void handleMessage(Message msg) {\n\t\t\tswitch (msg.what) {\n\t\t\t\tcase REPORT_LOCATION:\n\t\t\t\t\tonReportLocation();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 2:\n\t\t\t\t//\t\t\t\tpost();\n\t\t\t\t\tgetTime();\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate void getTime() {\n\n\t\tSimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss"); // HH:mm:ss\n\t\t//获取当前时间\n\t\tDate date = new Date(System.currentTimeMillis());\n\t\tString time = simpleDateFormat.format(date);\n\t\tString[] firstArray = time.split("\s");\n\t\n\t\t\tbinding.tvData.setText(firstArray[0]);\n\t\t\tbinding.tvTime.setText(firstArray[1]);\n\t\t\tif (!MainActivity.this.isDestroyed()) {\n\t\t\t\tmHandler.sendEmptyMessageDelayed(2 , 1000);\n\t\t\t}\n\n\t} 该代码是一个ReportLocationHandler类的handleMessage方法,根据传入的Message对象的what属性进行不同的处理。\n\n当msg.what等于REPORT_LOCATION时,调用onReportLocation()方法进行处理。\n\n当msg.what等于2时,调用getTime()方法进行处理。\n\ngetTime()方法中,使用SimpleDateFormat类获取当前时间,并将其格式化为"yyyy年MM月dd日 HH:mm:ss"的格式。然后将时间字符串拆分为日期和时间两部分,分别设置到对应的TextView上。最后使用Handler发送一个延迟为1秒的延迟消息,以实现每秒更新一次时间的效果。\n\n由于代码中存在mHandler.sendEmptyMessageDelayed(2 , 1000)语句,所以有时候会每次跳2秒更新一次时间,这可能是为了优化性能而设定的。\n\n为了解决每次跳2秒更新时间的问题,可以将mHandler.sendEmptyMessageDelayed(2 , 1000)语句改为mHandler.sendEmptyMessageDelayed(2 , 1000 * 0.5),这样可以实现每秒更新一次时间的效果。\n\n此外,还可以使用SystemClock.uptimeMillis()方法来获取系统启动以来的时间,这样可以避免由于系统时间被修改而导致的计时偏差。\n\n最终,代码应该如下:\n\n"class ReportLocationHandler extends Handler {\n\n\t\t@Override\n\t\tpublic void handleMessage(Message msg) {\n\t\t\tswitch (msg.what) {\n\t\t\t\tcase REPORT_LOCATION:\n\t\t\t\t\tonReportLocation();\n\t\t\t\t\tbreak;\n\t\t\t\tcase 2:\n\t\t\t\t//\t\t\t\tpost();\n\t\t\t\t\tgetTime();\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate void getTime() {\n\n\t\tSimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss"); // HH:mm:ss\n\t\t//获取当前时间\n\t\tDate date = new Date(SystemClock.uptimeMillis());\n\t\tString time = simpleDateFormat.format(date);\n\t\tString[] firstArray = time.split("\s");\n\t\n\t\t\tbinding.tvData.setText(firstArray[0]);\n\t\t\tbinding.tvTime.setText(firstArray[1]);\n\t\t\tif (!MainActivity.this.isDestroyed()) {\n\t\t\t\tmHandler.sendEmptyMessageDelayed(2 , 1000 * 0.5);\n\t\t\t}\n\n\t} "\n

Android时钟倒计时代码优化分析 - 如何解决跳秒问题

原文地址: https://www.cveoy.top/t/topic/pwKy 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录