2012年5月20日 星期日

Handler 03 + Timer



Handler and Timer

http://weizhulin.blog.51cto.com/1556324/323922



import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

public class Cq_Handler04Activity extends Activity {
    /** Called when the activity is first created. */

private int title = 0;
private Handler mHandler = new Handler() {

@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
//super.handleMessage(msg);
switch (msg.what) {
case 1:
updateTitle();
break;
}
}
};


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
     
        Timer timer = new Timer();
        timer.scheduleAtFixedRate(new MyTask(), 1, 1000);
    }
 
    private class MyTask extends TimerTask{

@Override
public void run() {
// TODO Auto-generated method stub
Message message = new Message();
message.what = 1;
mHandler.sendMessage(message);
}
   
    }
 
 
    public void updateTitle() {
    setTitle("Welcome to CQ's palace: " + title);
    title ++;
    }
}

沒有留言:

張貼留言