问题
I have a chronometer in Mainactivity.java
I wanted to save the starting time using SharedPreferences
and get the starting time show it in another activity but I can't figure out how to do so .I've tried Service
which allows it running in the background but it failed as it can't pass the variable to another activity and people suggested using SharedPreferences
would be easier. So does anyone knows how to save the starting time and get the value in another activity? Here's the code.
MainActivity.java
public class MainActivity extends AppCompatActivity{
private Chronometer chronometer;
protected FirebaseAuth firebaseauth = FirebaseAuth.getInstance();
@Override
protected void onStart(){
super.onStart();
chronometer.setBase(SystemClock.elapsedRealtime());
final long startTime = (SystemClock.elapsedRealtime() - chronometer.getBase());
final SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
final SharedPreferences.Editor editor = pref.edit();
@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"));
}
@Override
public void onCancelled (DatabaseError databaseError){
}
});
SecondActivity.java
@Override
protected void onStart() {
super.onStart();
final SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
mChildReference1.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String status = dataSnapshot.getValue(String.class);
// firebase status is occupied start chronometer
if(status.equals("occupied")) {
savedTime = pref.getLong("time",01);
chronometer.setBase(savedTime);
chronometer.getBase();
chronometer.setVisibility(View.VISIBLE);
}
if(!status.equals("occupied")){
chronometer.setBase(SystemClock.elapsedRealtime());
pauseOffset = 0;
chronometer.stop();
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
回答1:
if you are using the sharedpreference only in one activity it's ok to use getDefaultSharedPreferences() or getPreferences() methods on your activity.but in your case(as mentioned in the documentation) which is using one sharedPreference for multiple activities, you should assign a name to the sharedpreference.
this way the activity knows to get which of your sharedpreferences. just change this in your code
SharedPreferences pref = getSharedPreferences("chornometer", Context.MODE_PRIVATE);
for more information read the documentation
来源:https://stackoverflow.com/questions/58777436/how-to-save-chronometer-time-and-retrieve-it-in-another-activity-using-sharedpre