android主线程和子线程之间消息传递详解
从主线程发送消息到子线程(准确地说应该是非UI线程)
packagecom.zhuozhuo; importandroid.app.Activity; importandroid.os.Bundle; importandroid.os.Handler; importandroid.os.Looper; importandroid.os.Message; importandroid.util.Log; importandroid.view.View; importandroid.view.View.OnClickListener; publicclassLooperThreadActivityextendsActivity{ /**Calledwhentheactivityisfirstcreated.*/ privatefinalintMSG_HELLO=0; privateHandlermHandler; @Override publicvoidonCreate(BundlesavedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.main); newCustomThread().start();//新建并启动CustomThread实例 findViewById(R.id.send_btn).setOnClickListener(newOnClickListener(){ @Override publicvoidonClick(Viewv){//点击界面时发送消息 Stringstr="hello"; Log.d("Test","MainThreadisreadytosendmsg:"+str); mHandler.obtainMessage(MSG_HELLO,str).sendToTarget();//发送消息到CustomThread实例 } }); } classCustomThreadextendsThread{ @Override publicvoidrun(){ //建立消息循环的步骤 Looper.prepare();//1、初始化Looper mHandler=newHandler(){//2、绑定handler到CustomThread实例的Looper对象 publicvoidhandleMessage(Messagemsg){//3、定义处理消息的方法 switch(msg.what){ caseMSG_HELLO: Log.d("Test","CustomThreadreceivemsg:"+(String)msg.obj); } } }; Looper.loop();//4、启动消息循环 } } }
从非UI线程传递消息到UI线程(界面主线程),因为主界面已经有MessageQueue,所以可以直接获取消息处理消息。而上面由主线程向非UI线程中处理消息的时候,非UI线程需要先添加消息队列,然后处理消息循环。
publicclassThreadHandlerActivityextendsActivity{ /**Calledwhentheactivityisfirstcreated.*/ privatestaticfinalintMSG_SUCCESS=0;//获取图片成功的标识 privatestaticfinalintMSG_FAILURE=1;//获取图片失败的标识 privateImageViewmImageView; privateButtonmButton; privateThreadmThread; privateHandlermHandler=newHandler(){ publicvoidhandleMessage(Messagemsg){//此方法在ui线程运行 switch(msg.what){ caseMSG_SUCCESS: mImageView.setImageBitmap((Bitmap)msg.obj);//imageview显示从网络获取到的logo Toast.makeText(getApplication(),getApplication().getString(R.string.get_pic_success),Toast.LENGTH_LONG).show(); break; caseMSG_FAILURE: Toast.makeText(getApplication(),getApplication().getString(R.string.get_pic_failure),Toast.LENGTH_LONG).show(); break; } } }; @Override publicvoidonCreate(BundlesavedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.main); mImageView=(ImageView)findViewById(R.id.imageView);//显示图片的ImageView mButton=(Button)findViewById(R.id.button); mButton.setOnClickListener(newOnClickListener(){ @Override publicvoidonClick(Viewv){ if(mThread==null){ mThread=newThread(runnable); mThread.start();//线程启动 } else{ Toast.makeText(getApplication(),getApplication().getString(R.string.thread_started),Toast.LENGTH_LONG).show(); } } }); } Runnablerunnable=newRunnable(){ @Override publicvoidrun(){//run()在新的线程中运行 HttpClienthc=newDefaultHttpClient(); HttpGethg=newHttpGet("http://csdnimg.cn/www/images/csdnindex_logo.gif");//获取csdn的logo finalBitmapbm; try{ HttpResponsehr=hc.execute(hg); bm=BitmapFactory.decodeStream(hr.getEntity().getContent()); }catch(Exceptione){ mHandler.obtainMessage(MSG_FAILURE).sendToTarget();//获取图片失败 return; } mHandler.obtainMessage(MSG_SUCCESS,bm).sendToTarget();//获取图片成功,向ui线程发送MSG_SUCCESS标识和bitmap对象 //mImageView.setImageBitmap(bm);//出错!不能在非ui线程操作ui元素 //mImageView.post(newRunnable(){//另外一种更简洁的发送消息给ui线程的方法。 // //@Override //publicvoidrun(){//run()方法会在ui线程执行 //mImageView.setImageBitmap(bm); //} //}); } };
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。