There are two main uses for a Handler: (1) to schedule messages and runnables to be executed as some point in the future; and (2) to enqueue an action to be performed on a different thread than your own.
(1)如下就是handler sendMsg的简单工作原理图(post同理参考http://developer.android.com/reference/android/os/Handler.html):
(2)转载例子解释:
public final boolean post (Runnable r)
Causes the Runnable r to be added to the message queue. The runnable will be run on the thread to which this handler is attached.
例子(转载)
Handler Post方法虽然发送的是一个实现了Runnable接口的类对象,但是它并非创建了一个新线程,而是执行了该对象中的run方法。也就是说,整个run中的操作和主线程处于同一个线程。
这样对于那些简单的操作,似乎并不会影响。但是对于耗时较长的操作,当它被加入到消息队列中之后执行会占用很长的时间,以至于处于同一线程的其他操作无法继续执行,就会出现“假死”。为了解决这个问题,就需要使得handler绑定到一个新开启线程的消息队列上,在这个处于另外线程的上的消息队列中处理传过来的Runnable对象和消息。
- public class HandlerTest2 extends Activity {
- 2.
- 3. @Override
- 4. protected void onCreate(Bundle savedInstanceState) {
- 5. // TODO Auto-generated method stub
- 6. super.onCreate(savedInstanceState);
- 7. setContentView(R.layout.main);
- 8. //打印了当前线程的ID
- 9. System.out.println("Activity-->" + Thread.currentThread().getId());
- 10.
- 11. //生成一个HandlerThread对象
- 12. HandlerThread handlerThread = new HandlerThread("handler_thread");
- 13. //在使用HandlerThread的getLooper()方法之前,必须先调用该类的start(),同时开启一个新线程;
- 14. handlerThread.start();
- 15. //将由HandlerThread获取的Looper传递给Handler对象,即由处于另外线程的Looper代替handler初始化时默认绑定的消息队列来处理消息。
- 16. //自定义Handler
- 17. MyHandler myHandler = new MyHandler(handlerThread.getLooper());
- 18. Message msg = myHandler.obtainMessage();
- 19. //将msg发送到目标对象,所谓的目标对象,就是生成该msg对象的handler对象
- 20. Bundle b = new Bundle();
- 21. b.putInt("age", 20);
- 22. b.putString("name", "Jhon");
- 23. msg.setData(b);
- 24. msg.sendToTarget();//将msg发送到myHandler
- 25. }
- 26.
- 27. //自定义Handler类
- 28. class MyHandler extends Handler{
- 29. public MyHandler(){
- 30.
- 31. }
- 32.
- 33. public MyHandler(Looper looper){
- 34. super(looper);
- 35. }
- 36. //这里的handleMessage将在子线程handlerThread中执行而不是在主线程中执行
- 37. @Override
- 38. public void handleMessage(Message msg) {
- 39. Bundle b = msg.getData();
- 40. int age = b.getInt("age");
- 41. String name = b.getString("name");
- 42. System.out.println("age is " + age + ", name is" + name);
- 43. System.out.println("Handler--->" + Thread.currentThread().getId()); System.out.println("handlerMessage");
- 44. }
- 45. }
- 46. }