此方法针对于无法自动获取网络时间的特殊设备,正常 Android 设备直接调用
System.currentTimeMillis();
方法获取当前时间即可。
TimeService 集成于 Service,实现与主Activity 的生命周期绑定。
TimeService 代码
public class TimeService extends Service { private TimeService mContext; private Timer mTimer;//定时器 private long currentTimeMillis = 0;//当前时间 private static final long UPDATE_TIME_OFFSET = 1 * 1000;//自动更新间隔 private CheckTimeTask checkTimeTask; private UpdateTimeTask updateTimeTask; //需用内部类继承Binder,并定义方法获取Service对象 private final IBinder binder = new TimeBinder(); //外部调用,获取当前时间 public long getCurrentTimeMillis() { return currentTimeMillis; } //初始化服务时间 public void setCurrentTimeMillis(String dateStr) { if (StringUtil.isNullOrEmpty(dateStr)) { return; } try { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = sdf.parse(dateStr); currentTimeMillis = date.getTime(); } catch (ParseException e) { e.printStackTrace(); } } public class TimeBinder extends Binder { public TimeService getService() { return mContext; } } @Nullable @Override public IBinder onBind(Intent intent) { return binder; } @Override public void onCreate() { super.onCreate(); mContext = this; initData(); } private void initData() { mTimer = new Timer(); checkTimeTask = new CheckTimeTask(); updateTimeTask = new UpdateTimeTask(UPDATE_TIME_OFFSET); mTimer.schedule(checkTimeTask, 1000, 5 * 60 * 1000);//每5分钟更新一次网络时间 mTimer.schedule(updateTimeTask, 0, UPDATE_TIME_OFFSET); } @Override public void onDestroy() { super.onDestroy(); if (mTimer != null) { mTimer.cancel(); mTimer = null; } if (checkTimeTask != null) { checkTimeTask.cancel(); checkTimeTask = null; } if (updateTimeTask != null) { updateTimeTask.cancel(); updateTimeTask = null; } } /** * 获取服务器时间 */ private class CheckTimeTask extends TimerTask { @Override public void run() { //=========此处为获取网络时间请求======== //=============================== SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); if (bean != null ) { String dateStr = bean; try { Date date = sdf.parse(dateStr); currentTimeMillis = date.getTime(); } catch (ParseException e) { e.printStackTrace(); } } } } /** * 定时更新当前时间 */ private class UpdateTimeTask extends TimerTask { /** * 更新时间间隔 */ private long offset = 0; public UpdateTimeTask(long offset) { this.offset = offset; } @Override public void run() { currentTimeMillis += offset; } }}