FirstDemoActivity
public class MyDemoActivity extends AppCompatActivity { public static final int SET = 1; //设置一个what标记 private TextView info = null; //文本显示组件 private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case SET: //判断标志位 MyDemoActivity.this.info.setText("当前时间为:" + msg.obj.toString()); //设置显示时间 break; } } }; /** * 显示时间类 */ private class ClockTread implements Runnable { @Override public void run() { while (true) { Message msg = MyDemoActivity.this.handler.obtainMessage(MyDemoActivity .SET, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"). format(new Date())); //实例化Message MyDemoActivity.this.handler.sendMessage(msg); //发送消息 try { Thread.sleep(1000); //延迟1s } catch (InterruptedException e) { e.printStackTrace(); } } } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); super.setContentView(R.layout.activity_main); this.info = (TextView)findViewById(R.id.info); new Thread(new ClockTread()).start(); // 启动线程 } }
2. activity_main.xml
<AnalogClock android:id="@+id/AnalogClock" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:id="@+id/info" android:layout_width="fill_parent" android:layout_height="wrap_content" />
普通的方法是无法直接刷新UI界面的,这时需要借助Handler发送给主线程消息传递数据。
原文:http://my.oschina.net/u/1414017/blog/527970