回顾上一集内容:
首先在UI Thread(Main Thread)创建一个Handler对象, 复写其HandlerMessage方法
在Worker Thread里面调用Handler的SendMessage来发送消息
消息会被发送到消息队列里面, Looper会从队列中取出并给主线程HandlerMessage处理
这种机制实现从WorkerThread发送消息给MainThread
这一集:
这个过程与上一篇相反
由MainThread里面的Handler发送消息, WorkerThread里面的HandlerMessage来处理
总共分为3个步骤:
1. 准备Looper对象
2. 在WorkerThread当中生成Handler对象
3. 在MainThread当中发送消息
1 public static class PlaceholderFragment extends Fragment { 2 3 private Button button; 4 private Handler handler; 5 6 public PlaceholderFragment() { 7 } 8 9 @Override10 public View onCreateView(LayoutInflater inflater, ViewGroup container,11 Bundle savedInstanceState) {12 View rootView = inflater.inflate(R.layout.fragment_main, container, false);13 14 button = (Button)rootView.findViewById(R.id.buttonId);15 button.setOnClickListener(new OnClickListener() { //匿名内部类写法!!!!! 16 public void onClick(View v) {17 Log.i("tag","onClick--->" + Thread.currentThread().getName());18 Message msg = handler.obtainMessage();19 handler.sendMessage(msg);20 }21 });22 23 WorkerThread wt = new WorkerThread();24 wt.start();25 26 return rootView;27 }28 29 class WorkerThread extends Thread{30 //固定写法!!!!31 @Override32 public void run() {33 //准备Looper对象34 Looper.prepare();35 //在WorkerThread中生成一个Handler对象36 handler = new Handler(){37 public void handleMessage(Message msg) {38 Log.i("tag","handlerMessage--->" + Thread.currentThread().getName());39 Log.i("tag","Message Reiceved!!!");40 }41 };42 //调用Looper的loop方法之后,Looper方法将不断从消息队列中取出消息对象,然后调用Handler的HandlerMessage处理该消息对象43 //如果消息队列没有消息, 则线程阻塞44 Looper.loop();45 } 46 }47 }