I was making a small update to MagicPlayer and stumbled upon this puzzling way of handling concurrency.
Can you figure out what it does? (Some irrelevant code snipped)
Class: TracData
public class TrackData extends Handler {
String artist, album, track;
CallBack cb;
Context ctx;
public TrackData(Context ctx, CallBack cb) {
this.ctx = ctx;
this.cb = cb;
}
@Override
public void handleMessage(Message msg) {
if(msg.what == 1) {
cb.setData(this.artist, this.album, this.track);
}
}
public void get(final int sid) {
new Thread() {
public void run() {
TalkWithTheServer();
obtainMessage(1).sendToTarget();
}
}.start();
}
interface CallBack {
public void setData(String artist, String album, String track);
}
}
And another Class: TrackInfo
public class TrackInfo extends Activity implements TrackData.CallBack {
TextView txtArtist;
TextView txtAlbum;
TextView txtTrack;
@Override
public void onCreate(Bundle savedInstanceState) {
SetupStuff();
fetchData(id_of_song_that_is_playing);
}
private void fetchData(int sid) {
TrackData d = new TrackData(this, this);
d.get(sid);
}
@Override
public void setData(String artist, String album, String track) {
txtArtist.setText(artist);
txtAlbum.setText(album);
txtTrack.setText(track);
}
}
!!!!!SPOILER!!!!!
TrackData is background fetcher which gets some data from my server and upon receiving it, updates the text fields in the UI. It looks a bit weird, but I figured this was clean way of doing it with as little code as possible.
TrackInfo is just an Activity with some fields for the returned data. It implements the TracData's inner interface to receive the data when TrackData has done talking.