在开发系统设置时,需要手动设置系统时间和使用网络时间来进行同步,这时候就需要来获取网络时间进行设置了 代码如下:
URL url = new URL("http://www.baidu.com");//取得资源对象
URLConnection uc = url.openConnection();//生成连接对象
uc.connect(); //发出连接
long ld = uc.getDate(); //取得网站日期时间
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(ld);
final String format = formatter.format(calendar.getTime());
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
Log.e("MainActivity","year:"+year+"--month:"+month+"---day:"+day+"---hour:"+hour+"---minute:"+minute+"--format:"+format);
((AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE)).setTime(
calendar.getTimeInMillis());