Android开发之实时更新系统时间

实现功能跟手机的时间一样,可模仿秒钟的跳动,实时更新时间到textView中

封装的方法:

/**
 * 时间变化handler
 */
@SuppressLint("HandlerLeak")
private Handler handler = new Handler() {
    @SuppressLint("SetTextI18n")
    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        //通过消息的内容msg.what  分别更新ui
        switch (msg.what) {
            case MSG_ONE:
                //获取到系统当前时间 long类型
                currentTimeMillis = System.currentTimeMillis();
                //将long类型的时间转换成日历格式
                mDate = new Date(currentTimeMillis);
                // 转换格式,年月日时分秒 星期  的格式
                if (systemState) {//是否使用24小时制
                    if (secondState) {//是否显示秒
                        tv_show_time.setText(twentyFourMinuteTimeFormat.format(mDate));
                    } else {
                        tv_show_time.setText(twentyFourTimeFormat.format(mDate));
                    }
                } else {
                    Calendar calendar = Calendar.getInstance();
                    int i = calendar.get(Calendar.AM_PM);
                    if (secondState) {//是否显示秒

                        if (i == 0) {
                            tv_show_time.setText("上午" + "\n" + twelveMinuteTimeFormat.format(mDate));
                        } else if (i == 1) {
                            tv_show_time.setText("下午" + "\n" + twelveMinuteTimeFormat.format(mDate));
                        }
                    } else {
                        if (i == 0) {
                            tv_show_time.setText("上午" + "\n" + twelveTimeFormat.format(mDate));
                        } else if (i == 1) {
                            tv_show_time.setText("下午" + "\n" + twelveTimeFormat.format(mDate));
                        }
                    }
                }
                //显示在textview上,通过转换格式
                break;
            default:
                break;
        }
    }
};

/**
 * 开启一个线程,每个一秒钟更新时间
 */
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);
    }
}

猜你喜欢

转载自blog.csdn.net/freak_csh/article/details/79625918