android实现textview显示系统时间

首先在main_activity.xml文件中建立一个id=ShowTime的文本框。

再在MianActivity.java中编写方法(该方法用到了异步消息线程机制,讲解如下:)

Handler、Looper、Message都是与Android异步消息处理线程相关的概念。

异步消息处理线程启动后会进入一个无限的循环体之中,每循环一次,从其内部的消息队列中取出一个消息,然后回调相应的消息处理函数,执行完成一个消息后则继续循环。若消息队列为空,线程则会阻塞等待。

private TextView tv_time; //先建立textview对象
private static final int x=1; //建立静态常量相当于计时器
public class timeThread extends Thread{ //建立方法实现线程
public void run(){
do{
try{
Thread.sleep(1000); //每一秒建立一条消息,
Message message = new Message();
message.what=x;
mHandler.sendMessage(message); //Handler负责创建消息,
//Looper负责创建messageQueue并无线循环读取消息
}catch(InterruptedException e){
e.printStackTrace();
}
}while(true);
}
}
private Handler mHandler = new Handler(){ //用到了匿名内部类
public void handleMessage(Message message){
super.handleMessage(message);
switch(message.what){
case x:
long systime = System.currentTimeMillis();
Date date = new Date(systime);
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss EEEEEEEEE");
tv_time.setText(format.format(date));
break;
default:
break;
}
}
};




  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值