搜尋此網誌

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));
        }
        
    }
    

}

Surface View example

package my.surface;

import android.app.Activity;
import android.graphics.Canvas;
import android.graphics.Color;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class SurfaceActivity extends Activity {
    SurfaceActivity.MyCallBack myCallBacks = new MyCallBack();
    SurfaceView sView = null; //Create an abstract view which can display something later.
    SurfaceHolder sHolder = null;//with holder to do actual painting
    
    //This class is created for actual behaviors when meets following status :surface create , destroy and change
    private class MyCallBack implements SurfaceHolder.Callback{

        public void surfaceChanged(SurfaceHolder holder, int format, int width,
                int height) {
            
        }

        public void surfaceCreated(SurfaceHolder holder) {
            Canvas canvas = holder.lockCanvas();
            canvas.drawColor(Color.GREEN);
            holder.unlockCanvasAndPost(canvas);
        }

        public void surfaceDestroyed(SurfaceHolder holder) {
            
        }
        
    }
    
    public void onCreate (Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        sView = new SurfaceView(this);//This activity is treated as a context for the surface view.
        sHolder = sView.getHolder();//get a holder from this view to do control.
        sHolder.addCallback(myCallBacks);
        setContentView(sView);
    }

}