public class TestHandler extends Activity {
public static final int SLEEP_TIME = 300;
protected static final int GUIUPDATEIDENTIFIER = 0x101;
Thread myRefreshThread = null;
BounceView myBounceView = null;
Handler myHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case TestHandler.GUIUPDATEIDENTIFIER:
if (msg.arg1 == 2) {
myBounceView.x -= 20;
}
myBounceView.invalidate();
break;
}
super.handleMessage(msg);
}
};
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.myBounceView = new BounceView(this);
this.setContentView(this.myBounceView);
new Thread(new myThread(1)).start();
new Thread(new myThread(2)).start();
/*
* new Thread( new Runnable() { public void run() { while(true){
* Log.i("inner thead1"
* ,myBounceView.x+"--"+Thread.currentThread().getName());
* //myBounceView.invalidate(); //invalidate must be called from UI
* thread myBounceView.postInvalidate(); try { Thread.sleep(SLEEP_TIME);
* } catch (InterruptedException e) { // TODO Auto-generated catch block
* e.printStackTrace(); } }
*
* } }).start(); new Thread( new Runnable() { public void run() {
* while(true){ myBounceView.x-=20;
* Log.i("inner thead2",myBounceView.x+"--"
* +Thread.currentThread().getName()); myBounceView.postInvalidate();
* try { Thread.sleep(SLEEP_TIME); } catch (InterruptedException e) { //
* TODO Auto-generated catch block e.printStackTrace(); } }
*
* } }).start();
*/
Log.i("main thead", "--" + Thread.currentThread().getName());
}
class myThread implements Runnable {
private int cnt;
public myThread(int cnt) {
// TODO Auto-generated constructor stub
this.cnt = cnt;
}
public void run() {
while (!Thread.currentThread().isInterrupted()) {
Log.i("mythead " + cnt, "--" + Thread.currentThread().getName());
Message message = new Message();
message.what = TestHandler.GUIUPDATEIDENTIFIER;
message.arg1 = cnt;
myHandler.sendMessage(message);
try {
Thread.sleep(SLEEP_TIME);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}
}
貌似自己手动写thread也能实现handle的功能,handle应该是类库封装的更简便的操作,通过invalidate和handle可能都是在消息队列中添加一消息,然后在主线程从消息队列中获取一个消息,然后更新UI