android sendEmptyMessage()和sendMessage()误用导致handleMessage出现错误



在项目当中有电池管理的部分,当通过485接口发送指令给电池矩阵并正确返回数据后是调用了代码中的 onDataReceived 方法,通过里面的子线程获得数据,然后通过handler将数据发送到主线程做分析和UI修改等工作,但由于不注意sendMesage的使用,在代码当中开始这样编写:

 		Message mMessage = cmdHander.obtainMessage();
                String receiveStr = new String("adbjjdd");
                tempData += receiveStr;
//                mMessage.what = 1000;
                cmdHander.sendEmptyMessage(1000);
                mMessage.obj = tempData;
                Log.d("TIEJIANG", "tempData-1 = " + tempData);
                cmdHander.sendMessage(mMessage);
                Log.d("TIEJIANG", "tempData-2 = " + tempData);
                Log.d("TIEJIANG", "onDataReceived---receiveStr-send = " + receiveStr);

然后在handleMessage当中进行处理,

 private Handler cmdHander = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            Log.d("TIEJIANG", "cmdHandler");
            super.handleMessage(msg);

//			Log.d("TIEJIANG", "tempData = " + tempData);
//			Log.d("TIEJIANG", "tempData length = " + tempData.length());
            Log.d("TIEJIANG", "(String) msg.obj-1 = " + msg.obj);
        }
    };

发现收到了null!具体Log信息:

02-08 10:02:18.193 9166-9166/ D/TIEJIANG: tempData-1 = adbjjdd
02-08 10:02:18.193 9166-9166/ D/TIEJIANG: tempData-2 = adbjjdd
02-08 10:02:18.193 9166-9166/ D/TIEJIANG: onDataReceived---receiveStr-send = adbjjdd
02-08 10:02:18.226 9166-9166/ D/TIEJIANG: cmdHandler
02-08 10:02:18.226 9166-9166/ D/TIEJIANG: (String) msg.obj-1 = null
02-08 10:02:18.226 9166-9166/ D/TIEJIANG: cmdHandler
02-08 10:02:18.226 9166-9166/ D/TIEJIANG: (String) msg.obj-1 = adbjjdd
从中可见,msg.obj先是null然后才有了数据。仔细观察子线程里面的代码才发现,我首先通过cmdhandler发送了一个message,即:
 cmdHander.sendEmptyMessage(1000);

然后才使用了

cmdHander.sendMessage(mMessage);
所以导致第一次并没有从“obj”里面拿到正确的数据。而正确的通过handler发送字符到主线程应该这样:

Message mMessage = cmdHander.obtainMessage();
                String receiveStr = new String("adbjjdd");
                tempData += receiveStr;
                mMessage.what = 1000;
//                cmdHander.sendEmptyMessage(1000);
                mMessage.obj = tempData;
                Log.d("TIEJIANG", "tempData-1 = " + tempData);
                cmdHander.sendMessage(mMessage);
                Log.d("TIEJIANG", "tempData-2 = " + tempData);
                Log.d("TIEJIANG", "onDataReceived---receiveStr-send = " + receiveStr);

你可能感兴趣的:(android sendEmptyMessage()和sendMessage()误用导致handleMessage出现错误)