2015年5月5日 星期二

[Android] thread communicate with UI thread by using message

put A part in thread, A part will send messages to main thread(UI thread). That is a way for sub thread to communicate with UI Thread.
A part:
// mainHandler.sendEmptyMessage(0); 
 Bundle result = new Bundle();
 result.putInt("P2Pdone", 1); 
 Message msg = new Message();
 msg.setData(result);
 msg.what = 4; // message number
 mainHandler.sendMessage(msg);

B part:
class MainHandler extends Handler {
  static final int MSGTYPE_LOG =1;
  static final int MSGTYPE_P2PTUNNEL_LOG=2;
  static final int MSGTYPE_P2PLIVE_LOG=3;
  
  @Override
  public void handleMessage(Message msg) {  
   handleMsg(msg);
   super.handleMessage(msg);
  }
  
  void handleMsg(Message msg)
  {
   switch(msg.what){
    case MSGTYPE_LOG:    //1
     _printLog((String)msg.obj);
     break;
    
    case MSGTYPE_P2PTUNNEL_LOG:   //2
     {

     }
     break;
    case MSGTYPE_P2PLIVE_LOG:    //3 , ken
//     txt_log.append(data+"\n");
     txt_log.append(msg.getData().getString("data")+"\n");
     break;  
    case 4:    //4 , ken
     if(msg.getData().getInt("P2Pdone")==1){
      uiSwitch(SC_START);
     }
     
    default:;
   }
  }
 }

沒有留言:

張貼留言