Android - 获取系统时间和网络时间
本文在开源项目GitHub中已收录,里面包含不同方向的自学编程路线、面试题集合/面经、及系列技术文章等,资源持续更新中…列技术文章等,资源持续更新中…**[外链图片转存中…(img-dB9oHsi0-1710333079074)][外链图片转存中…(img-FB7gD3g0-1710333079075)][外链图片转存中…(img-Vg3snRpW-1710333079075)]
3.MainActivity.class主界面中的逻辑
package com.mythmayor.gettime;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.net.URL;
import java.net.URLConnection;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class MainActivity extends Activity implements View.OnClickListener {
private TextView tvNetTime;
private Button btnNetTime;
private Button btnLocalTime;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/** 初始化控件 */
initView();
/** 处理用户输入 */
handleUserInput();
}
private void initView() {
tvNetTime = (TextView) findViewById(R.id.tv_nettime);
btnNetTime = (Button) findViewById(R.id.btn_nettime);
btnLocalTime = (Button) findViewById(R.id.btn_localtime);
}
private void handleUserInput() {
btnNetTime.setOnClickListener(this);
btnLocalTime.setOnClickListener(this);
}
private void getNetTime() {
URL url = null;//取得资源对象
try {
url = new URL(“http://www.baidu.com”);
//url = new URL(“http://www.ntsc.ac.cn”);//中国科学院国家授时中心
//url = new URL(“http://www.bjtime.cn”);
URLConnection uc = url.openConnection();//生成连接对象
uc.connect(); //发出连接
long ld = uc.getDate(); //取得网站日期时间
DateFormat formatter = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(ld);
final String format = formatter.format(calendar.getTime());
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, “当前网络时间为: \n” + format, Toast.LENGTH_SHORT).show();
tvNetTime.setText(“当前网络时间为: \n” + format);
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
private void getLocalTime() {
URL url = null;//取得资源对象
try {
DateFormat formatter = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
String format = formatter.format(calendar.getTime());
Toast.makeText(this, “当前系统时间为: \n” + format, Toast.LENGTH_SHORT).show();
tvNetTime.setText(“当前系统时间为: \n” + format);
} catch (Exception e) {
e.printStackTrace();
}
最后
本文在开源项目GitHub中已收录,里面包含不同方向的自学编程路线、面试题集合/面经、及系列技术文章等,资源持续更新中…
目前已经更新的部分资料,需要的自己取:
列技术文章等,资源持续更新中…**
目前已经更新的部分资料,需要的自己取:
[外链图片转存中…(img-dB9oHsi0-1710333079074)]
[外链图片转存中…(img-FB7gD3g0-1710333079075)]
[外链图片转存中…(img-Vg3snRpW-1710333079075)]
更多推荐
所有评论(0)