When I learned about callback functions in Android, it literally created a whole new world of possibilities of what I could do withing my apps. For so long I had used callback functions without even knowing it! An example of a callback function we all already use is with buttons and the onClickListener(). Usually when you create a button, you register a listener, and then you put code into it, like so:
Button btn = (Button) findViewById(yada_yada_yada);
btn.setOnclickListener(new OnClickListener(){
@Override
public void onClick(View v){
// do something
}
});
Basically, whenever you press a button, it sends a callback to this listener you set, and your program can do whatever you want in here. What we want to do now is replicate this sort of callback, but not for a button press. We want to replicate this for ANYTHING! In the example code I provide, we can now do things like this:
rst = new RandomSenderThingy();
rst.setRandomThingyListener(new RandomSenderThingyListener(){
@Override
public void onBoolThingChanged(boolean changed) {
Log.d("DEBUG","Callback Received! It is: " + changed);
}
});
The example code makes use of a few various techniques to get the point across, but I’ve clearly commented the parts that you will need to inject into your own code to get this functionality. Good luck and post any questions or comments in the comments section!
Download the source code here
-Kevin Grant