Android-Handler, Thread, Runnable的简单应用

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




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值