Android开发网络时间的获取与每秒的自动刷新
2018年01月20日 23:07:57 juer2017 阅读数:4573
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/juer2017/article/details/79117535
效果图:
1.布局一个TextView显示时间activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/black"
android:gravity="center">
<TextView
android:id="@+id/tv_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@color/white"
android:textSize="30sp" />
</LinearLayout>
2.java核心代码
package com.cwj.time;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.WindowManager;
import android.widget.TextView;
import java.net.URL;
import java.net.URLConnection;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity {
private TextView tv_time;
public static final int MSG_ONE = 1;
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
//通过消息的内容msg.what 分别更新ui
switch (msg.what) {
case MSG_ONE:
//获取网络时间
//请求网络资源是耗时操作。放到子线程中进行
new Thread(new Runnable() {
@Override
public void run() {
getNetTime();
}
}).start();
break;
default:
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
int flag = WindowManager.LayoutParams.FLAG_FULLSCREEN;
getWindow().setFlags(flag, flag);
setContentView(R.layout.activity_main);
initView();
new TimeThread().start();
}
//开一个线程继承Thread
public class TimeThread extends Thread {
//重写run方法
@Override
public void run() {
super.run();
// do-while 一 什么什么 就
do {
try {
//每隔一秒 发送一次消息
Thread.sleep(1000);
Message msg = new Message();
//消息内容 为MSG_ONE
msg.what = MSG_ONE;
//发送
handler.sendMessage(msg);
} catch (InterruptedException e) {
e.printStackTrace();
}
} while (true);
}
}
private void initView() {
tv_time = findViewById(R.id.tv_time);
}
private void getNetTime() {
URL url = null;//取得资源对象
try {
url = new URL("http://www.baidu.com");
//url = new URL("http://www.ntsc.ac.cn");//中国科学院国家授时中心
URLConnection uc = url.openConnection();//生成连接对象
uc.connect(); //发出连接
long ld = uc.getDate(); //取得网站日期时间
DateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日\n\nHH:mm:ss");
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(ld);
final String format = formatter.format(calendar.getTime());
runOnUiThread(new Runnable() {
@Override
public void run() {
tv_time.setText(format);
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}
3.既然是获取网络时间最后一定要在配置文件中加上联网权限
<!--联网权限-->
<uses-permission android:name="android.permission.INTERNET" />