FirstActivityjava
public class FirstActivity extends AppCompatActivity { private static int count = 0; public static final int SET = 1; //設置一個what標記 private Handler myHandle = new Handler() { //定義Handler對象 @Override public void handleMessage(Message msg) { switch (msg.what) { //判斷操做類型 case SET: FirstActivity.this.info.setText("dailei---"+count++); } super.handleMessage(msg); } }; private TextView info = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); super.setContentView(R.layout.activity_main); this.info = (TextView)findViewById(R.id.info); Timer timer = new Timer(); //定義調度器 timer.schedule(new MyTask(),0,1000); //當即開始,每隔1秒增加 } /** * 定義定時調度的具體實現類 */ private class MyTask extends TimerTask{ @Override public void run() { Message msg = new Message(); //定義message msg.what = SET; //操做爲設置顯示文字 FirstActivity.this.myHandle.sendMessage(msg); //發送消息到子線程 } } }
2. activity_main.xml
android
<TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/info"/>