Handler默认是运行在主UI线程中的,如果想创建子线程中的Handler,可以使用HandlerThread和Handler类配合使用,如下所示:
private static final class UserCenterThread extends HandlerThread {
public UserCenterThread(String name) {
super(name);
}
public UserCenterThread(String name, int priority) {
super(name, priority);
}
}
private static final class UserCenterHandler extends Handler { // 子线程中的Handler
private final WeakReference<UserCenterHelper> mWeakRef;
public UserCenterHandler(final Looper looper, final UserCenterHelper helper) {
super(looper);
mWeakRef = new WeakReference<UserCenterHelper>(helper);
}
@Override
public void handleMessage(Message msg) {
final UserCenterHelper helper = mWeakRef.get();
if (null == helper) {
return;
}
HelperOperateItem item = null;
ResultToken token = null;
if (msg.obj instanceof ResultToken) {
token = (ResultToken) msg.obj;
final String helperUserData = token.mUserData;
item = helper.removeOperateItem(helperUserData);
if (null == item) {
return;
}
} else {
return;
}
XLLog.d(TAG, "msg:what[" + msg.what + "]error[" + msg.arg1 + "]optType[" + item.mOperateType
+ "]helperUserData[" + item.mHelperUserData + "]");
switch (item.mOperateType) {
case TYPE_OPERATE_QUERY_WEBSITES:
helper.handleQeuryWebsiteResult(token.mResultObj, msg.arg1, item);
break;
case TYPE_OPERATE_DEL_WEBSITE_TEL:
helper.handleDelWebsiteToTel(msg.arg1, item);
break;
case TYPE_OPERATE_DEL_WEBSITE_CNC:
helper.handleDelWebsiteToCnc(msg.arg1, item);
break;
case TYPE_OPERATE_QUERY_CINEMAS:
helper.handleQeuryCinemasResult(token.mResultObj, msg.arg1, item);
break;
case TYPE_OPERATE_DEL_CINEMAS_TEL:
helper.handleDelCinemasToTel(msg.arg1, item);
break;
case TYPE_OPERATE_DEL_CINEMAS_CNC:
helper.handleDelCinemasToCnc(msg.arg1, item);
break;
case TYPE_OPERATE_QUERY_SITCOMS:
helper.handleQeurySitcomsResult(token.mResultObj, msg.arg1, item);
break;
case TYPE_OPERATE_DEL_SITCOM_TEL:
helper.handleDelSitcomToTel(token.mResultObj, msg.arg1, item);
break;
case TYPE_OPERATE_DEL_SITCOM_CNC:
helper.handleDelSitcomToCnc(token.mResultObj, msg.arg1, item);
break;
default:
break;
}
}
}
使用:
mThread = new UserCenterThread(TAG);
mThread.start();
mHelperHandler = new UserCenterHandler(mThread.getLooper(), this);