安卓开发过程中,有时候会用到实时的显示当前时间的功能,比如:自定义的状态栏就需要实时的更新当前时间,看下面图就是自定义的状态栏实时的更新时间:
实时显示更新时间代码:TimeThread.java
import android.os.Handler;
import android.os.Message;
import android.widget.TextView;import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;/*** Copyright: Copyright (c) 2017-2025* Class: 实时更新时间的线程** @author: 赵小贱* @date: 2017/9/13* describe:*/
public class TimeThread extends Thread {public TextView tvDate;private int msgKey1 = 22;public TimeThread(TextView tvDate) {this.tvDate = tvDate;}@Overridepublic void run() {do {try {Thread.sleep(1000);Message msg = new Message();msg.what = msgKey1;mHandler.sendMessage(msg);} catch (InterruptedException e) {e.printStackTrace();}} while (true);}private Handler mHandler = new Handler() {@Overridepublic void handleMessage(Message msg) {super.handleMessage(msg);switch (msg.what) {case 22:SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");String date = sdf.format(new Date());tvDate.setText(date + getWeek());break;default:break;}}};/*** 获取今天星期几* @return*/public static String getWeek() {Calendar cal = Calendar.getInstance();int i = cal.get(Calendar.DAY_OF_WEEK);switch (i) {case 1:return "周日";case 2:return "周一";case 3:return "周二";case 4:return "周三";case 5:return "周四";case 6:return "周五";case 7:return "周六";default:return "";}}
}
调用代码:MainActivity.java
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
/*** Copyright: Copyright (c) 2017-2025* Class: 主方法* @author: 赵小贱* @date: 2017/9/13* describe:*/
public class MainActivity extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);TextView tvDate= (TextView) findViewById(R.id.tv_date);//实时更新时间(1秒更新一次)TimeThread timeThread = new TimeThread(tvDate);//tvDate 是显示时间的控件TextViewtimeThread.start();//启动线程}}
源码下载地址:http://download.csdn.net/download/zhaoxiaojian1213/9977254
安卓监听WiFi信号的变化:http://blog.csdn.net/zhaoxiaojian1213/article/details/77976504
安卓自定义电量显示图标:http://blog.csdn.net/zhaoxiaojian1213/article/details/77977505