I know what callback method is, but i'm confused what is the use of it?
We can make a call to another function from an calling function, then why pass reference to function as an argument ?
I see lot of callback methods being used in Android and I need to know what and how exactly these work.
Ankit Singhaniya
Full Stack Developer
Great question! Callbacks are exactly what it sounds like.
Call me back, when x is done.This is the whole premise of callback, so why pass callback when we can call a method instead, true. Just think, will this make a very reusable code?Let's say today you are writing a piece of code which based on phone battery health send SMS to the users family that the phone may die. To do this you have called a method call
alertFamilyOnLowBattery, now let's say the requirements have changed and you also want to send an email to some of the freindemailPalsOnLowBattery. You see this right, you will be requested to do a lot of things as the user keeps on requesting new features(which will happen).Now as you have the power of callback, your library says
hi, give a me a method to execute whenever the battery is below the limit.This just one inversion of responsibility has made you code so much reusable. You can now host it on GitHub for other people to use, who are building a software to hibernate apps if battery is low.I hope that helps. :)