我們知道,在做網絡異步請求的時候,有時候需要在收到數據時進行一些界面的更新,為了更簡單地與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() {
@Override
public void callBack() {
NotificationHelper.updateNotification(Integer.valueOf(song.song_id),
"下載 " + song.name + " 完成", file.getAbsolutePath(), true);
song.local_location = getSongLocalLocation(song);
song.is_local = true;
if(handler != null)
handler.sendMsg("adapter_notify", null);
Toast.makeText(aq.getContext(), aq.getContext().getString(R.string.toast_download_finished),
Toast.LENGTH_SHORT).show();
}
},null);
}
});
}