首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android Handler 子線程發送異類消息導致崩潰:msg.obj 類型不一致

     編輯:程式設計綜合問答

錯誤代碼


// 下載圖片
byte[] data = ...;
Message msg = Message.obtain();
msg.obj = data;          // byte[]
msg.what = IS_FINISH;
handler.sendMessage(msg);

// 下載文字
Message ms = Message.obtain();
ms.obj = "haha";         // String
ms.what = IS_OK;
handler.sendMessage(ms);

// Handler 處理
public void handleMessage(Message msg) {
    byte[] data = (byte[]) msg.obj; // 此處崩潰:String 無法轉 byte[]
    ...
}

原因

msg.obj 類型不一致:圖片消息為 byte[],文字消息為 String。handleMessage 統一按 byte[] 強轉,處理文字消息時拋 ClassCastException。

修正方案

  1. 區分 what 處理:
    
      public void handleMessage(Message msg) {
          switch (msg.what) {
              case IS_FINISH:
                  byte[] data = (byte[]) msg.obj;
                  Bitmap bmp = BitmapFactory.decodeByteArray(data, 0, data.length);
                  imageView.setImageBitmap(bmp);
                  break;
              case IS_OK:
                  String text = (String) msg.obj; // 正確轉型
                  textView.setText(text);
                  break;
          }
      }
      
  2. 統一封裝數據類:
    
      class Result { int type; byte[] bytes; String text; }
      // 發送時 new Result{type=1, bytes=data}
      // 處理時 (Result)msg.obj 統一轉型
      

最佳實踐

  • 每個 what 對應固定 obj 類型,文檔化約定。
  • 使用 Message.obj 傳遞數據時,優先用 Bundle (setData/getData) 類型安全。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved