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

来源:互联网 发布:全国地区数据库 编辑:程序博客网 时间:2024/05/22 03:27

动态显示系统时间

参考博文: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();            }    }}
原创粉丝点击