0

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!

sam
  • 2,780
  • 1
  • 17
  • 30
Jaswanth Kumar
  • 3,531
  • 3
  • 23
  • 26

1 Answers1

2

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.

sam
  • 2,780
  • 1
  • 17
  • 30
  • I'm getting "method findViewById(int) is undefined" for the class..How can I resolve this? – Jaswanth Kumar Jan 02 '15 at 16:38
  • @JaswanthKumar well, it is defined in View class. You need to find a way to access to it from your code: http://developer.android.com/reference/android/app/Activity.html#findViewById(int) – sam Jan 02 '15 at 16:55
  • Anyway, I could do this without chronometer.getbase()? – Jaswanth Kumar Jan 03 '15 at 05:33
  • well, if you can track the initial base time of your chronometer, you don't have to call getbase() method. What you need is just to get the difference in time between resume and pause. – sam Jan 03 '15 at 05:36
  • Tried this but isn't working: At Pause: timeWhenStopped = SystemClock.elapsedRealtime(); remoteView.setChronometer(R.id.notification_timer, timeWhenStopped, null, false); At Resume: timeWhenResumed = SystemClock.elapsedRealtime() - timeWhenStopped; remoteView.setChronometer(R.id.notification_timer,timeWhenResumed, null, true); – Jaswanth Kumar Jan 03 '15 at 05:53
  • Your code is incorrect. Please read my code's logic more carefully. Time difference is the start time of chronometer subtracted by elapsedRealtime. And when you resume, you need to set the base time as elapsedRealtime added by the time difference. – sam Jan 03 '15 at 07:20