我想知道在使用handleMessage接口时如何使用switch-case。如下面的代码所示,在run()方法中我发送不同的消息 我只有一个带handleMessage()接口的处理程序,我想知道如何使用switch-case来处理发送的不同消息
onCreate中的:
private void initObjs() {
Log.w(TAG, CSubTag.bullet("initObjs"));
this.mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
..
..
}
};
}
运行()中的:
public void run() {
//initiating connection
BluetoothSocket rfcSocket = mSPPCtrl.rfcConnect();
if (rfcSocket.isConnected()) {
Message msg = mHandler.obtainMessage();
Bundle b = new Bundle();
b.putString("CONNECTED", "RFC-SOCKET CONNECTED");
msg.setData(b);
mHandler.sendMessage(msg);
//assigning stream variables
try {
this.mRFCOS = rfcSocket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
try {
this.mRFCIS = rfcSocket.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
} else {
Message msg = mHandler.obtainMessage();
Bundle b = new Bundle();
b.putString("DISCONNECTED", "RFC-SOCKET NOT CONNECTED");
msg.setData(b);
mHandler.sendMessage(msg);
}
答案 0 :(得分:0)
,给msg.what一个int值,比如0,1,2 ...
,使用swith case;
答案 1 :(得分:0)
定义消息常量,如
public static final int STATE_CONNECTED = 1;
public static final int STATE_DISCONNECTED = 2;
处理程序:
@Override
public void handleMessage(Message msg) {
switch(msg.what) {
case STATE_CONNECTED:
//do your stuff
break;
case STATE_DISCONNECTED:
//do your stuff
break;
default :
//default condition
break;
}
}
在run()
中public void run() {
...
if (rfcSocket.isConnected()) {
Message msg = mHandler.obtainMessage(STATE_CONNECTED);
...
} else {
Message msg = mHandler.obtainMessage(STATE_DISCONNECTED);
...
}
}