Runnable:Represents a command that can be executed. Often used to run code in a different Thread
.
一、既然Runnable和Thread有关,我们先实现Runnable类,在需要执行的过程中,创建一个Thread出来。
在Thread调用start()方法后,会执行调用Runnable对象中的run()方法。而往往Thread对象在主线程的创建,以“同步”占用CPU资源。
class AnimationThread implements Runnable {
private final String TTAG = "AnimationThread";
private float newX;
private float newY;
private final float gap = 2;
private View animView;
public AnimationThread(View view, float X, float Y) {
Log.d(TTAG, "Constructor:AnimationThread");
newX = X;
newY = Y;
animView = view;
}
@Override
public void run() {
// TODO Auto-generated method stub
Log.d(TTAG, "AnimationThread::run");
float scale = Math.abs(newY - ry) / Math.abs(newX - rx);
float xx = rx;
float yy = ry;
while (newX != xx && newY != yy) {
if (newX > xx) {
xx += gap;
if (newX < xx) {
xx = newX;
}
}else if(newX < xx) {
xx -= gap;
if (newX > xx) {
xx = newX;
}
}
if (newY > yy) {
yy += gap * scale;
if (newY < yy) {
yy = newY;
}
}else if (newY < yy) {
yy -= gap * scale;
if (newY > yy) {
yy = newY;
}
}
setRX(xx);
setRY(yy);
setRadius();
try {
Message msg = new Message();
msg.obj = view;
handler.sendMessage(msg);
Thread.sleep(50);
}catch(Exception ex) {
}
}
}
}
二、在看Handler的官方overview:A Handler allows you to send and process Message
and Runnable objects associated with a thread's MessageQueue
. Each Handler instance is associated with a single thread and that thread's message queue. When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it -- from that point on, it will deliver messages and runnables to that message queue and execute them as they come out of the message queue.
从以上看,每个Handler实例和单个线程及线程的消息队列相关,允许Handler发送和处理消息。那我们在Runnable的run()方法内部加入Handler的sendMessage,在Handler的handleMessage中处理相关消息。
private Handler mMsgHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
((View)msg.obj).invalidate();
}
};
invalidate()调用view的刷新函数onDraw()。
public MyTrackBallView(Context context) {
super(context);
Log.d(TAG, "Constructor:MyTrackBallView");
radius = 20;
mBChangeRadius = false;
setOnTouchListener(this);
}
@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
Log.d(TAG, "onDraw");
Paint p = new Paint();
p.setColor(Color.BLUE);
canvas.drawCircle(getRX(), getRY(), getRadius(), paint);
}