安卓APP

开发核心思想是理解发布订阅模式,UI线程是主线程,网络请求是另外的子线程,子线程不能直接更新UI,只能通过消息通知主线程,让主线程去更新UI。

子线程和主线程通过一个handler通信,子线程在主线程那边订阅事件,即发生了A事件,主线程进行更新UI操作A(如改变按钮颜色等),发生B事件,主线程进行更新UI操作B。

子线程进行网络请求,发出message通知主线程更新UI

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
public void run() {
try {
MomaRequest jsonObjectGetRequest = new MomaRequest(Request.Method.GET,
MOMA_CAR_INFO_URL + this.query, null,
new Response.Listener<NetworkResponse>() {

@Override
public void onResponse(NetworkResponse response) {
String str_response = new String(response.data);
mLog.d(MomaLOG.TAG, "car info detail response" + str_response);

CarMsg ygMsg = new CarMsg(response);
Message msg = mUiHandler.obtainMessage();
if (ygMsg.parseMessage() == MomaReturnCode.YG_RET_SUCCESS) {
msg.obj = str_response; // 此处需校验后台数据合法性
msg.what = MomaInnerMessage.MSG_CAR_DETAIL_QUERY_SUCCESS;
} else {
msg.what = MomaInnerMessage.MSG_PARSER_ERROR;
msg.obj = null;
}
mUiHandler.sendMessage(msg);

}
}, new Response.ErrorListener() {

@Override
public void onErrorResponse(VolleyError volleyError) {
mLog.d(MomaLOG.TAG, "volleyError" + volleyError);
}
});
String localCookieStr = mYGService.getCookiesMgr().getLoginCookies();
jsonObjectGetRequest.setSendCookie(localCookieStr); // 向服务器发起post请求时加上cookie字段

mRequestQueue.add(jsonObjectGetRequest);
} catch (Exception e) {
mLog.d(MomaLOG.TAG, "Error:" + e);
}

}

这里是事件订阅,即不同事件类型对应不同的UI更新操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
private Handler mUiHandler = new Handler() {

public void handleMessage(Message msg) {
try {
switch (msg.what) {
case MomaInnerMessage.MSG_NETWORK_CONNECTED: {
break;
}
case MomaInnerMessage.MSG_YG_SERVICE_GET: {
mLog.d(MomaLOG.TAG, "msg ---- car info page,service get.");
initDataAfterGetService();
break;
}
case MomaInnerMessage.MSG_CAR_QUERY_SUCCESS: {
mLog.d(MomaLOG.TAG, "msg ---- car info page,query success.");
updateQuery(msg.obj.toString());
break;
}
case MomaInnerMessage.MSG_CAR_DETAIL_QUERY_SUCCESS: {
mLog.d(MomaLOG.TAG, "msg ----query car detail data: " + msg.obj);
updateAfterSelectCar(msg.obj.toString());
break;
}
case MomaInnerMessage.MSG_SAVE_NEW_CAR_DATA_SUCCESS: {
mLog.d(MomaLOG.TAG, "msg ----save data success");
Toast.makeText(getApplicationContext(), "保存成功", Toast.LENGTH_SHORT).show();
break;
}
default: {
break;
}
}
} catch (Exception e) {
mLog.d(MomaLOG.TAG, "Error:" + e);
}
}

;
};