Android——线程中的通信(一)练习

动态显示系统时间

参考博文:http://www.cnblogs.com/zyw-205520/archive/2013/01/30/2883649.html

SimpleDateFormat
Formats and parses dates in a locale-sensitive manner. Formatting turns a Date into a String, and parsing turns a String into a Date.
简单就是将日期转换成字符串

Date
A specific moment in time, with millisecond precision. Values typically come from currentTimeMillis(), and are always UTC, regardless of the system’s time zone. This is often called “Unix time” or “epoch time”.
获取系统时间,标准的日期格式

思路:主线程创建handler,并定义如何处理获取的信息。子线程启动
子线程创建进程,并定义子线程传入消息的内容

public class MainActivity extends Activity implements Runnable{
    private Handler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        final TextView textView=(TextView) findViewById(R.id.textView1);

        handler = new Handler() {
            public void handleMessage(Message msg) {
                textView.setText((String)msg.obj);
            }
        };

        new Thread(this).start();        
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
         try {
                while(true){
                    SimpleDateFormat sdf=new SimpleDateFormat("yyyy年MM月dd日   HH:mm:ss");
                    String str=sdf.format(new Date());
                    handler.sendMessage(handler.obtainMessage(100,str));
                    Thread.sleep(1000);
                }
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值