Android(1)-Handler Looper Message MessageQueue
http://www.cnblogs.com/TS-qrt/articles/android.html
Android学习笔记——从源码看Handler的处理机制
http://www.cnblogs.com/yjiyjige/p/3145052.html
一:
发送:
class myThread implementsRunnable {
public voidrun() {
while (!Thread.currentThread().isInterrupted()) {
Message message = new Message();
message.what = TestHandler.GUIUPDATEIDENTIFIER;
TestHandler.this.myHandler.sendMessage(message);
}
}
}
接收:
Handler myHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case TestHandler.GUIUPDATEIDENTIFIER:
myBounceView.invalidate();
break;
}
super.handleMessage(msg);
}
};
二:
发送:
MyHandler myHandler = new MyHandler(handlerThread.getLooper());
Message msg = myHandler.obtainMessage();
//将msg发送到目标对象,所谓的目标对象,就是生成该msg对象的handler对象
Bundle b = new Bundle();
b.putInt("age", 20);
b.putString("name", "Jhon");
msg.setData(b);
msg.sendToTarget(); //将msg发送到myHandler
接收:
@Override
public void handleMessage(Message msg) {
Bundle b = msg.getData();
int age = b.getInt("age");
String name = b.getString("name");
}
}
三:
发送:
@Override
public void run() {
currentItem=(currentItem + 1) % adListData.size();
Message msg=new Message();
msg.arg1=currentItem;
mHandler.sendMessage(msg);
}
接收:
final Handler mHandler=new Handler(){
public void handleMessage(Message msg) {
mViewPager.setCurrentItem(msg.arg1);
}};
四:
// 当前轮播页
private int currentItem = 0;
final Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
mViewPager.setCurrentItem(currentItem); //注意这里并没有用到参数msg
}
};
Executors.newScheduledThreadPool(1).scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
synchronized (mViewPager) {
currentItem = (currentItem + 1) % mList.size();
handler.obtainMessage().sendToTarget();
}
}
}, 0, 5, TimeUnit.SECONDS);
Handler sendMessage 与 obtainMessage (sendToTarget)比较 :
http://www.cnblogs.com/android007/archive/2012/05/10/2494766.html 写的很好!
总结:
Message message = Message.obtain();
message.arg1 = 1;
message.arg2 = 2;
message.obj = "Demo";
message.what = 3;
Bundle bundleData = new Bundle();
bundleData.putString("Name", "Lucy");
message.setData(bundleData);
在Android中可以通过handler方法完成数据的线程间的传递,但一定要将handler得到的数据通过loop传递到主线程再更新UI吗?其实也可以直接使用handler设计的post方法进行实现,handler的post方法是在主线程运行的,可以直接进行UI的更新操作。
privateHandler myhandler=
new
Handler();
mHandler.post
(new
Runnable() {
@Override
public
void
run() {
Bitmap bm=BitmapFactory.decodeByteArray(data,
0
,data.length );
imageView.setImageBitmap(bm);
}
};
);