You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android通知中如何将Chronometer格式设置为HH:MM:SS?

Android通知中Chronometer显示HH:MM:SS格式的解决办法

默认调用remoteViews.setChronometer(R.id.myChronometer, elapsedTime, null, true)时,小时数小于10会显示为一位数(如1:12:35),要改成两位数的HH:MM:SS格式(如01:12:35),可以试试以下两种方案:

方案一:利用setChronometer的格式参数

setChronometer的第三个参数支持传入自定义格式字符串,直接指定"HH:mm:ss"即可:

remoteViews.setChronometer(R.id.myChronometer, elapsedTime, "HH:mm:ss", true);

注意:部分旧Android版本可能不支持该格式,建议在目标版本上测试验证。

方案二:用TextView模拟计时(兼容性更好)

如果方案一不生效,可放弃Chronometer,改用TextView结合定时任务实现:

  1. 将通知布局中的Chronometer替换为TextView
  2. 编写定时更新逻辑,手动格式化时间为HH:MM:SS格式:
// 计算初始已流逝的总秒数(elapsedTime为计时起始时间戳)
long totalSeconds = (System.currentTimeMillis() - elapsedTime) / 1000;
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder notificationBuilder = /* 你的通知构建器 */;
RemoteViews remoteViews = /* 你的RemoteViews实例 */;

Handler timerHandler = new Handler();
Runnable timerTask = new Runnable() {
    @Override
    public void run() {
        totalSeconds++;
        // 格式化时间为HH:MM:SS
        int hours = (int) (totalSeconds / 3600);
        int minutes = (int) ((totalSeconds % 3600) / 60);
        int seconds = (int) (totalSeconds % 60);
        String formattedTime = String.format("%02d:%02d:%02d", hours, minutes, seconds);
        
        // 更新TextView内容并刷新通知
        remoteViews.setTextViewText(R.id.myTimerTextView, formattedTime);
        notificationManager.notify(NOTIFICATION_ID, notificationBuilder.build());
        
        // 1秒后再次执行
        timerHandler.postDelayed(this, 1000);
    }
};

// 启动计时
timerHandler.post(timerTask);

这种方式不受系统版本限制,兼容性更强,但需要手动处理通知的刷新逻辑。

内容的提问来源于stack exchange,提问作者montassar zarroug

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 05:50:17