I am triying to add Chronometer inside service and fetch value.But i am not getting correct Chronometer value.
public class NewLocationUpdateService extends Service {
Chronometer chronometer;
private static final int LOC_API_CALL_INTERVAL = 60 * 1000;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
chronometer = new Chronometer(NewLocationUpdateService.this);
chronometer.setBase(SystemClock.elapsedRealtime());
chronometer.start();
startTimer();
return START_NOT_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
return binder;
}
@Override
public boolean onUnbind(Intent intent) {
return super.onUnbind(intent);
}
@Override
public void onDestroy() {
super.onDestroy();
stopTimer();
}
//Timer related functions
private void startTimer(){
if(timer!=null ){
return;
}
timer=new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
long millis=SystemClock.elapsedRealtime() - chronometer.getBase();
long seconds = (millis / 1000) % 60;
Log.e("timefortest", "" + seconds);
}
}, LOC_API_CALL_INTERVAL, LOC_API_CALL_INTERVAL);
}
private void stopTimer(){
if(null!=timer){
timer.cancel();
timer=null;
}
}
}
The output i am getting
E/timefortest: 7
E/timefortest: 1
E/timefortest: 0
E/timefortest: 5
E/timefortest: 0
E/timefortest: 0
E/timefortest: 0
E/timefortest: 0
E/timefortest: 1
E/timefortest: 0
E/timefortest: 2
i am expecting
E/timefortest: 60
E/timefortest: 120
E/timefortest: 180
E/timefortest: 240
let me know what i did wrong.my purpose is i need to start counter inside service and i need to fetch the value.
I think you should remove the mod 60.here is an example.