问题场景:
最近开发中遇到一个bug,在设置日期和时间时,手动设置时间,开关机时间正常.使用自动获取网络时间,连接可上网的网络,获取时间也是正常.
但在使用静态IP时或者网络不可上网时,获取的时间就是异常的.
问题分析:
代码如下:
private void setAutoTime() {
if (isNetworkAvalible(getActivity())) {
Log.d("setRTCTime", "===setAutoTime===isNetworkAvalible====");
final Calendar calendar = Calendar.getInstance();
new Thread(new Runnable() {
@Override
public void run() {
URL urlTime = null;//取得资源对象
try {
urlTime = new URL("https://www.baidu.com");
URLConnection uc = urlTime.openConnection();//生成连接对象
uc.setConnectTimeout(3000);
uc.connect(); //发出连接
long autoTime = uc.getDate(); //取得网站日期时间
Date date = new Date(autoTime); //转换为标准时间对象
date.getDate();
Log.d("setRTCTime", "===setAutoTime===autoTime====" + autoTime);
if (autoTime == 0) {
return;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
}
public boolean isNetworkAvalible(Context context) {
// 获得网络状态管理器
ConnectivityManager connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager == null) {
return false;
} else {
// 建立网络数组
NetworkInfo[] net_info = connectivityManager.getAllNetworkInfo();
if (net_info != null) {
for (int i = 0; i < net_info.length; i++) {