Search code examples
androidandroid-notificationschronometer

How to pause and resume Chronometer in Notification Panel?


I have a chronometer in notification panel which I instantiate using

remoteView.setChronometer(R.id.notification_timer, SystemClock.elapsedRealtime(),
                          null, true);

How should I pause the timer and resume it when I call Pause/Play button on Notification Panel?

Thanks in advance!


Solution

  • Try this code when you pause:

    long timeDifference = 0;
    Chronometer chronometer = (Chronometer) findViewById(R.id.notification_timer);
    timeDifference  = chronometer.getBase() - SystemClock.elapsedRealtime();
    remoteView.setChronometer(R.id.notification_timer, SystemClock.elapsedRealtime(),
                              null, false);
    

    When you resume your timer,

    remoteView.setChronometer(R.id.notification_timer,
                              timeDifference + SystemClock.elapsedRealtime(), null, true);
    

    Hope this helps.