Thursday, 18 November 2010

Handler Puzzle

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;

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() {

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;
public void onCreate(Bundle savedInstanceState) {

private void fetchData(int sid) {
TrackData d = new TrackData(this, this);

public void setData(String artist, String album, String track) {


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.

No comments:

Post a Comment