Skip to content

Instantly share code, notes, and snippets.

@tankcong
Last active March 17, 2017 07:32
Show Gist options
  • Save tankcong/a9120956f23ea924c81c64b3f35843f4 to your computer and use it in GitHub Desktop.
Save tankcong/a9120956f23ea924c81c64b3f35843f4 to your computer and use it in GitHub Desktop.
Android application time synchronization, using android.os.SystemClock
import android.os.SystemClock;
import java.util.Date;
/**
* Created by tankcong
*/
public class ServerDate {
private Date serverDate;
private long initElapsedTime;
private static ServerDate INSTANCE;
public static ServerDate getInstance() {
if (INSTANCE == null) {
INSTANCE = new ServerDate();
}
return INSTANCE;
}
public boolean synced() {
return serverDate != null;
}
/**
* simple implementation, just set server date,
* replace with time synchronization logic.
*/
public void syncServer(Date serverDate) {
initElapsedTime = SystemClock.elapsedRealtime();
this.serverDate = serverDate;
}
public Date currentDateGMT() {
Date current = new Date(serverDate.getTime());
current.setTime(serverDate.getTime()
+ (SystemClock.elapsedRealtime() - initElapsedTime));
return current;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment