I am trying to get chronometer to maintain its time throughout different activities. I have the chronometer in a fragment that I have at the bottom of each activity. So basically once it switches from MainActivity to Corsi I want the clock to be the same.
MainActivity
public class MainActivity extends AppCompatActivity implements hold_undo_fragment.toggleButtonListener{
Chronometer chronometer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//runBeaconDistances();
chronometer = (Chronometer) findViewById(R.id.clock);
chronometer.setBase(SystemClock.elapsedRealtime());
chronometer.start();
}
public void toCorsi(View view){
Intent myIntent = new Intent(MainActivity.this.getBaseContext(), corsi.class);
myIntent.putExtra("time", chronometer.getBase() - SystemClock.elapsedRealtime()); // or thisSystemClock.elapsedRealtime() - chronometer.getBase() but neither works
startActivity(myIntent);
}
}
Corsi activity
public class corsi extends AppCompatActivity implements hold_undo_fragment.toggleButtonListener {
Chronometer chronometer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_corsi);
Bundle timeData = getIntent().getExtras();
if (timeData == null)
return;;
long millis = timeData.getLong("time");
chronometer = (Chronometer) findViewById(R.id.clock);
chronometer.setBase(millis);
chronometer.start();
}
}
and what happens is that once I enter main activity the clock starts from 00:00 and starts counting up (like it is supposed to). But once I switch to Corsi it gets the system time (27:00:..) which is not what I am trying to do. Please help, thank you.
You should start a service for this task. Subscribe/unsubscribe to updates from activities with a callback