I want to make stopwatch like in endomondo. When we launch application, it should count time and update textView in main activity (actually it is a fragment).
I did background service (like here)but well, it did not work. When I've changed the activity to the other one, service was counting time from the 0. The question is, what is the proper way to implement this? I now it is possible, I have to reproduce similar behaviour to endomondo's counter that when we start training it counts time all the time no matter if we change activity or minimalize the application. I've also tried to do this using foreground service, but sadly I've read that I can't update ui from it. I'm working on API Level 24.
What is the proper way to handle this?
create foreground service and use countDown timer. then every 1 second send broadcast to change ui. if you want your app be alive in background on android 8 and upper you should send notification with service to show to user, your app doing task.
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
int milliseconds = 100* 1000;
new CountDownTimer(milliseconds, 1000) {
@Override
public void onTick(long millisUntilFinished) {
Intent intent = new Intent("timer_tracking");
intent.putExtra("timer", millisUntilFinished);
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent);
}
@Override
public void onFinish() {
stopSelf();
}
}.start();
return START_STICKY;
}
and in activity/fragment after register broadcast_receiver use this code.
public BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
@SuppressLint("DefaultLocale")
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(MainActivity.this, "broad", Toast.LENGTH_LONG).show();
long millisUntilFinished = intent.getLongExtra("timer", 0);
String counter = String.format("%02d:%02d:%02d",
TimeUnit.MILLISECONDS.toHours(millisUntilFinished),
TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished),
TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished)));
textView.setText(counter);
}
};