欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

android主线程和子线程之间消息传递详解

程序员文章站 2024-03-31 12:03:04
从主线程发送消息到子线程(准确地说应该是非ui线程) package com.zhuozhuo; import android.app.activity; i...

从主线程发送消息到子线程(准确地说应该是非ui线程)

package com.zhuozhuo;
import android.app.activity;
import android.os.bundle;
import android.os.handler;
import android.os.looper;
import android.os.message;
import android.util.log;
import android.view.view;
import android.view.view.onclicklistener;

public class looperthreadactivity extends activity{
 /** called when the activity is first created. */
 
 private final int msg_hello = 0;
 private handler mhandler;
 
 @override
 public void oncreate(bundle savedinstancestate) {
  super.oncreate(savedinstancestate);
  setcontentview(r.layout.main);
  new customthread().start();//新建并启动customthread实例
  
  findviewbyid(r.id.send_btn).setonclicklistener(new onclicklistener() {
   
   @override
   public void onclick(view v) {//点击界面时发送消息
    string str = "hello";
    log.d("test", "mainthread is ready to send msg:" + str);
    mhandler.obtainmessage(msg_hello, str).sendtotarget();//发送消息到customthread实例
    
   }
  });
  
 }
 
 
 
 
 
 class customthread extends thread {
  @override
  public void run() {
   //建立消息循环的步骤
   looper.prepare();//1、初始化looper
   mhandler = new handler(){//2、绑定handler到customthread实例的looper对象
    public void handlemessage (message msg) {//3、定义处理消息的方法
     switch(msg.what) {
     case msg_hello:
      log.d("test", "customthread receive msg:" + (string) msg.obj);
     }
    }
   };
   looper.loop();//4、启动消息循环
  }
 }
}

从非ui线程传递消息到ui线程(界面主线程),因为主界面已经有messagequeue,所以可以直接获取消息处理消息。而上面由主线程向非ui线程中处理消息的时候,非ui线程需要先添加消息队列,然后处理消息循环。

public class threadhandleractivity extends activity {
 /** called when the activity is first created. */
 
 private static final int msg_success = 0;//获取图片成功的标识
 private static final int msg_failure = 1;//获取图片失败的标识
 
 private imageview mimageview;
 private button mbutton;
 
 private thread mthread;
 
 private handler mhandler = new handler() {
  public void handlemessage (message msg) {//此方法在ui线程运行
   switch(msg.what) {
   case msg_success:
    mimageview.setimagebitmap((bitmap) msg.obj);//imageview显示从网络获取到的logo
    toast.maketext(getapplication(), getapplication().getstring(r.string.get_pic_success), toast.length_long).show();
    break;

   case msg_failure:
    toast.maketext(getapplication(), getapplication().getstring(r.string.get_pic_failure), toast.length_long).show();
    break;
   }
  }
 };
 
 @override
 public void oncreate(bundle savedinstancestate) {
  super.oncreate(savedinstancestate);
  setcontentview(r.layout.main);
  mimageview= (imageview) findviewbyid(r.id.imageview);//显示图片的imageview
  mbutton = (button) findviewbyid(r.id.button);
  mbutton.setonclicklistener(new onclicklistener() {
   
   @override
   public void onclick(view v) {
    if(mthread == null) {
     mthread = new thread(runnable);
     mthread.start();//线程启动
    }
    else {
     toast.maketext(getapplication(), getapplication().getstring(r.string.thread_started), toast.length_long).show();
    }
   }
  });
 }
 
 runnable runnable = new runnable() {
  
  @override
  public void run() {//run()在新的线程中运行
   httpclient hc = new defaulthttpclient();
   httpget hg = new httpget("http://csdnimg.cn/www/images/csdnindex_logo.gif");//获取csdn的logo
   final bitmap bm;
   try {
    httpresponse hr = hc.execute(hg);
    bm = bitmapfactory.decodestream(hr.getentity().getcontent());
   } catch (exception e) {
    mhandler.obtainmessage(msg_failure).sendtotarget();//获取图片失败
    return;
   }
   mhandler.obtainmessage(msg_success,bm).sendtotarget();//获取图片成功,向ui线程发送msg_success标识和bitmap对象

//   mimageview.setimagebitmap(bm); //出错!不能在非ui线程操作ui元素

//   mimageview.post(new runnable() {//另外一种更简洁的发送消息给ui线程的方法。
//    
//    @override
//    public void run() {//run()方法会在ui线程执行
//     mimageview.setimagebitmap(bm);
//    }
//   });
  }
 };

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。