我们知道,在做网络异步请求的时候,有时候需要在收到数据时进行一些界面的更新,为了更简单地与UI主线程交互,我稍微封装了下。
[java]
import java.util.HashMap;
import java.util.Map;
import android.os.Handler;
import android.os.Message;
public class HandlerHelper {
public static class MyHandler extends Handler {
private Map<String, HandlerCallback> table_cb = new HashMap<String, HandlerCallback>();
@Override
public void handleMessage(Message msg) {
if(msg.what == 1) {
if(msg.obj != null) {
HandlerCallback _cb = (HandlerCallback)msg.obj;
_cb.callBack();
msg.what = 0;
}
}
super.handleMessage(msg);
}
public void sendMsg(HandlerCallback _cb, Object tag) {
_cb.tag = tag;
Message msg = new Message();
msg.what = 1;
msg.obj = _cb;
this.sendMessage(msg);
}
public void sendMsg(String key, Object tag) {
if(table_cb.containsKey(key)) {
HandlerCallback cb = table_cb.get(key);
cb.tag = tag;
Message msg = new Message();
msg.what = 1;
msg.obj = cb;
this.sendMessage(msg);
}
}
public void setHandlerCallback(String key, HandlerCallback _cb) {
table_cb.put(key, _cb);
}
}
public abstract static class HandlerCallback {
public Object tag;
public abstract void callBack();
}
}
tag是为了传递额外数据给UI主线程,具体用法:
[java]
private MyHandler mhandler = new MyHandler();
@Override
protected void onCreate(Bundle savedInstanceState) {
//...
mhandler.setHandlerCallback("music_status_refresh", new HandlerCallback() {
@Override
public void callBack() {
NotificationHelper.updateNotification();
adapter_songlist.notifyDataSetChanged();
if(pd.play_status == PublicData.PLAYSTATE_PLAYING) {
aq.id(R.id.amain_bottom_bar_title).text("正在播放:" + pd.song_nowpalying.name);
aq.id(R.id.amain_bottom_bar_info).text(pd.song_nowpalying.artist_name);
aq.id(R.id.amain_bottom_bar_icon).image(pd.song_nowpalying.album_logo, true, true, 0, 0);
aq.id(R.id.amain_bottom_bar).visible();
} else {
aq.id(R.id.amain_bottom_bar).gone();
}
}
});
mhandler.setHandlerCallback("adapter_notify", new HandlerCallback() {
@Override
public void callBack() {
adapter_songlist.notifyDataSetChanged();
}
});
pd.list_service_callback.add(mhandler);
setupView();
is_songlist_getting = true;
myapi.getSongList(list_song, list_now_type, next_page);
if(pd.setting_check_updata) {
UpdataHelper.checkUpdata(aq, false);
}
}
然后在网络异步回调时(mhandler_amain为上面的mhandler):
[java]
public void downloadSong(final Song song, final MyHandler handler) {
//...
aq.progress(new MyOnProgressListener(song)).download(song.location, target, new AjaxCallback<File>() {
@Override
public void callback(String url, final File file, AjaxStatus status) {
mhandler_amain.sendMsg(new HandlerCallback() {
补充:移动开发 , Android ,