Handler

* A Handler allows you to send and process {@link Message} and Runnable
* objects associated with a thread's {@link 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.
*
* <p>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.

/**
* Use the {@link Looper} for the current thread with the specified callback interface
* and set whether the handler should be asynchronous.
*
* Handlers are synchronous by default unless this constructor is used to make
* one that is strictly asynchronous.
*
* Asynchronous messages represent interrupts or events that do not require global ordering
* with respect to synchronous messages. Asynchronous messages are not subject to
* the synchronization barriers introduced by {@link MessageQueue#enqueueSyncBarrier(long)}.
*
* @param callback The callback interface in which to handle messages, or null.
* @param async If true, the handler calls {@link Message#setAsynchronous(boolean)} for
* each {@link Message} that is sent to it or {@link Runnable} that is posted to it.
*
* @hide
*/
public Handler(Callback callback, boolean async) {
if (FIND_POTENTIAL_LEAKS) {
final Class<? extends Handler> klass = getClass();
if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
(klass.getModifiers() & Modifier.STATIC) == 0) {
Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
klass.getCanonicalName());
}
}

mLooper = Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}


Handler是跨线程的;
Handler对象本身是一个堆对象;属于进程,线程共有。
线程外部通过它发送消息;
线程内部通过它处理消息;

  1. public class LoopThread implements Runnable {  
  2.   
  3.     public Handler mHandler = null;  
  4.   
  5.     @Override  
  6.     public void run() {  
  7.         Looper.prepare();  
  8.         mHandler = new Handler() {  
  9.             public void handleMessage(Message msg) {  
  10.                 String result = NetUtil.getJsonContent("北京");  
  11.                 //完成了获取北京天气的操作;  
  12.                 Log.i("test", "handler"+result);  
  13.             }  
  14.         };  
  15.         Looper.loop();  
  16.     }  
  17.   
  1. lThread.mHandler.sendEmptyMessage(0);  
原文地址:https://www.cnblogs.com/feng9exe/p/5950308.html