Android Message

[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; 
        }
    } 
  } 
};

 

Continue reading