android:layout_width=“match_parent”
android:layout_height=“wrap_content”
android:gravity=“center”
android:text=“Hello World!”
android:textSize=“22sp” />
<Button
android:id="@+id/btn_nettime"
android:layout_width=“match_parent”
android:layout_height=“wrap_content”
android:layout_marginTop=“20dp”
android:text=“获取当前网络时间”
android:textSize=“20sp” />
<Button
android:id="@+id/btn_localtime"
android:layout_width=“match_parent”
android:layout_height=“wrap_content”
android:layout_marginTop=“20dp”
android:text=“获取当前系统时间”
android:textSize=“20sp” />
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
《Android学习笔记总结+最新移动架构视频+大厂安卓面试真题+项目实战源码讲义》
浏览器打开:qq.cn.hn/FTe 免费领取
.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();
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_nettime:
//获取网络时间
//请求网络资源是耗时操作。放到子线程中进行
new Thread(new Runnable() {
@Override