[Android 開發] This message is already in use 解法

Handler 和 Message 是 Android 用來更新畫面的重要方法,有在開發 Android 的朋友都應該要知道這兩個的用法。而海芋最近使用這個方法來開發程式時,碰到了「android.util.AndroidRuntimeException: This message is already in use」這個問題,這是原本的寫法。

private int MSG_INCREASE_PROGRESSBAR = 9527;
private int MSG_Done = 5566;
private ProgressDialog m_progressDialog = null;

private Runnable m_runnable = new Runnable(){
  @Override
  public void run() {
    try {
      Message msg = new Message();
      for (int i = 0; i < 100; i++){
        msg.what = MSG_INCREASE_PROGRESSBAR;
        m_Handler.sendMessage(msg);
      }
 
      msg.what = MSG_Done;
      m_Handler.sendMessage(msg);
    }
    catch (Exception e) {
      e.printStackTrace();
    }
  } 
};

private Handler m_Handler = new Handler(){
  @Override
  public void handleMessage(Message msg) {
    super.handleMessage(msg);
    switch (msg.what){
      case MSG_INCREASE_PROGRESSBAR:
        if (m_progressDialog != null)
          m_progressDialog.incrementProgressBy(1);
        break;
      case MSG_DelteDone:
        if (m_progressDialog != null){
          m_progressDialog.dismiss(); 
          m_progressDialog = null; 
        }
    } 
  } 
};

 

出現這個問題,海芋就去追查一下 Handler 這個 Class,原來在 Handler SendMessage 後,Handler 會將 Message 加入 MessageQueue 中,造成原本要處理的對象,已經不是原來的對象所致,所以要解決這個問題,必須在每次傳送 Message 給 Handler 前,先 New 一個 Message 元件,所以改成以下的寫法就可以囉!

private int MSG_INCREASE_PROGRESSBAR = 9527;
private int MSG_Done = 5566;
private ProgressDialog m_progressDialog = null;

private Runnable m_runnable = new Runnable(){
  @Override
  public void run() {
    try {
      for (int i = 0; i < 100; i++){
        Message msg = new Message();
        msg.what = MSG_INCREASE_PROGRESSBAR;
        m_Handler.sendMessage(msg);
      }
      Message msg = new Message();
      msg.what = MSG_Done;
      m_Handler.sendMessage(msg);
    }
    catch (Exception e) {
      e.printStackTrace();
    }
  } 
};

private Handler m_Handler = new Handler(){
  @Override
  public void handleMessage(Message msg) 
  { 
     super.handleMessage(msg);
     switch (msg.what){
       case MSG_INCREASE_PROGRESSBAR:
         if (m_progressDialog != null)
           m_progressDialog.incrementProgressBy(1);
         break;
       case MSG_DelteDone:
         if (m_progressDialog != null){
           m_progressDialog.dismiss(); 
           m_progressDialog = null; 
         }
         break;
     }
  } 
};

 

About 張海芋

城市裡的小小迷僮工程師,喜歡用鍵盤記錄個人生活的點滴,身邊的人事物都我的靈感,用心踏出每個腳步,用文字灌溉《海芋小站》,用專業解決問題。

發表迴響