我的MainActivity
中有一个天文钟,我想保存经过的时间并将其传递给SecondActivity
,并显示经过的时间,并使用共享的首选项在第二个活动中继续运行它,但是我无法这样做。
我尝试使用textView来检查该值是否从主活动传递到第二个活动,但确实如此,但是涉及计时器时它不起作用,第二个活动中的计时器仍为0:00。
这是代码:MainActivity.java
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private Chronometer chronometer;
@Override
protected void onStart(){
super.onStart();
final long startTime = (SystemClock.elapsedRealtime() - chronometer.getBase());
chronometer.setBase(startTime);
final SharedPreferences pref = getSharedPreferences("chronometer",Context.MODE_PRIVATE);
final SharedPreferences.Editor editor = pref.edit();
mChildReference1.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange (DataSnapshot dataSnapshot){
String status = dataSnapshot.getValue(String.class);
if (status.equals ("occupied")) {
chronometer.start();
editor.putLong("time", startTime);
editor.commit();
}
else
mValueView1.setBackgroundColor(Color.parseColor("#66d983"));
}
SecondActivity.java
@Override
protected void onStart() {
super.onStart();
final SharedPreferences pref = getSharedPreferences("chronometer",Context.MODE_PRIVATE);
mChildReference1.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String status = dataSnapshot.getValue(String.class);
if(status.equals("occupied")) {
savedTime = pref.getLong("time",01);
timer.setText(String.valueOf(savedTime));
chronometer.setBase(savedTime);
chronometer.getBase();
}
if(!status.equals("occupied")){
chronometer.setBase(SystemClock.elapsedRealtime());
pauseOffset = 0;
chronometer.stop();
parkingCharge=0;
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});