搜尋此網誌

2012年6月1日 星期五

Android Handler demo

package my.handler;

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

public class HandlerDemoActivity extends Activity{
    
    int count = 0;
    public void onCreate (Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        final HandlerDemoActivity.MyHandler  handler = new MyHandler();
        Thread t = new Thread(){
            public void run(){
                while(true){
                    try {
                        Thread.sleep(2000);
                        Message msg = new Message();
                        Bundle msgBundle = new Bundle();
                        msgBundle.putInt("count", count);
                        msg.setData(msgBundle);
                        handler.sendMessage(msg);
                        count++;
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
    
                }
                                
            }
        };
        t.start();
    }
    
    class MyHandler extends Handler{
        public void handleMessage(Message msg){
            int i = (Integer) msg.getData().get("count");
            Log.d("handler", String.valueOf(i));
        }
        
    }
    

}

沒有留言:

張貼留言