简体   繁体   中英

Android Studio chronometer time through different activities

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM