1. 程式人生 > >Android定時器更新UI

Android定時器更新UI

TimerTask在重寫run,在run裡邊似乎是另一個執行緒,是不能直接更新UI的
初始化時:

    //定時器
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg){//處理訊息
            switch (msg.what){
                case 0:
                    addNewItem();//更新UI
                    break;
            }
} }; Timer timer = new Timer(); TimerTask task = new TimerTask() { @Override public void run() { Message msg = new Message(); msg.what = 0; msg.obj = 0; handler.sendMessage(msg);//定時器超時,傳送訊息 } };

onCreate時啟動定時器:

        timer.schedule(task,0,5000);