Android:用定时器 timer 刷新界面

Android:用定时器 timer 刷新界面

Posted by: tigerz on March 6, 2010

 android timer

在 Android 平台上,界面元素不能在定时器的响应函数里刷新。

以下这段代码中,mButton 的文本并不变化。

public class AndroidTimerDemo extends Activity {
    private Button mButton;
    private Timer mTimer;
    private TimerTask mTimerTask;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        mButton = (Button) findViewById(R.id.Button01);

        mTimer = new Timer();

        mTimerTask = new TimerTask() {

            @Override
            public void run() {
                Log.d("AndroidTimerDemo", "timer");
                Calendar cal = Calendar.getInstance();
                mButton.setText(cal.toString());
            }
        };

        mTimer.schedule(mTimerTask, 1000, 1000);
    }
}

在 Android 平台上,UI 单元必须在 Activity 的 context 里刷新。 为了达到想要的效果,可以使用 Message Handler。在定时器响应函数里发送条消息,在 Activity 里响应消息并更新文本。

public class AndroidTimerDemo extends Activity {
    protected static final int UPDATE_TEXT = 0;
    private Button mButton;
    private Timer mTimer;
    private TimerTask mTimerTask;
    private Handler mHandler;


    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        mButton = (Button) findViewById(R.id.Button01);

        mTimer = new Timer();

        mHandler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what){
                case UPDATE_TEXT:
                    Calendar cal = Calendar.getInstance();
                    mButton.setText(cal.toString());
                    break;
                }
            }
        };

        mTimerTask = new TimerTask() {

            @Override
            public void run() {
                Log.d("AndroidTimerDemo", "timer");
                mHandler.sendEmptyMessage(UPDATE_TEXT);
/* // It doesn't work updating the UI inside a timer. Calendar cal = Calendar.getInstance(); mButton.setText(cal.toString()); */          
                }
        };

        mTimer.schedule(mTimerTask, 1000, 1000);
    }
}

你可能感兴趣的:(timer,android,calendar,Class,button,平台)