publicclassMyThreadimplementsRunnable{// 在run方法中完成网络耗时的操作@Overridepublicvoidrun(){HttpClienthttpClient=newDefaultHttpClient();HttpGethttpGet=newHttpGet(imgPath);HttpResponsehttpResponse=null;try{Log.v("debug","start download picture in thread:"+Thread.currentThread().getName());httpResponse=httpClient.execute(httpGet);Log.v("debug","download complete with status code"+httpResponse.getStatusLine().getStatusCode());if(200==httpResponse.getStatusLine().getStatusCode()){byte[]data=EntityUtils.toByteArray(httpResponse.getEntity());// 这里的数据data我们必须发送给UI的主线程,所以我们通过Message的方式来做桥梁。Messagemessage=Message.obtain();message.obj=data;message.what=DOWNLOAD_IMG;handler.sendMessage(message);}}catch(Exceptione){// TODO: handle exception}}}
publicbooleansendMessageAtTime(Messagemsg,longuptimeMillis){booleansent=false;MessageQueuequeue=mQueue;if(queue!=null){msg.target=this;sent=queue.enqueueMessage(msg,uptimeMillis);}else{RuntimeExceptione=newRuntimeException(this+" sendMessageAtTime() called with no mQueue");Log.w("Looper",e.getMessage(),e);}returnsent;}
/** * Default constructor associates this handler with the queue for the * current thread. * * If there isn't one, this handler won't be able to receive messages. */publicHandler(){...mLooper=Looper.myLooper();if(mLooper==null){thrownewRuntimeException("Can't create handler inside thread that has not called Looper.prepare()");}mQueue=mLooper.mQueue;mCallback=null;}
使用提供的消息队列,而不是使用默认的。
12345678
/** * Use the provided queue instead of the default one. */publicHandler(Looperlooper){mLooper=looper;mQueue=looper.mQueue;mCallback=null;}
/** * Run the message queue in this thread. Be sure to call * {@link #quit()} to end the loop. */publicstaticvoidloop(){finalLooperme=myLooper();if(me==null){thrownewRuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");}finalMessageQueuequeue=me.mQueue;// Make sure the identity of this thread is that of the local process,// and keep track of what that identity token actually is.Binder.clearCallingIdentity();finallongident=Binder.clearCallingIdentity();for(;;){Messagemsg=queue.next();// might blockif(msg==null){// No message indicates that the message queue is quitting.return;}// This must be in a local variable, in case a UI event sets the loggerPrinterlogging=me.mLogging;if(logging!=null){logging.println(">>>>> Dispatching to "+msg.target+" "+msg.callback+": "+msg.what);}msg.target.dispatchMessage(msg);if(logging!=null){logging.println("<<<<< Finished to "+msg.target+" "+msg.callback);}// Make sure that during the course of dispatching the// identity of the thread wasn't corrupted.finallongnewIdent=Binder.clearCallingIdentity();if(ident!=newIdent){Log.wtf(TAG,"Thread identity changed from 0x"+Long.toHexString(ident)+" to 0x"+Long.toHexString(newIdent)+" while dispatching to "+msg.target.getClass().getName()+" "+msg.callback+" what="+msg.what);}msg.recycle();}}