I’m looking for concept explanations or example code, if possible
I’m new to (android) development and from what i’ve seen, there are a ton of “onEvent()” methods. for example, View.onClickListener(), onPageDownload, onProgressUpdate… i’ve noticed that everything starts with “on”, and i’m assuming that it implies the method is a callback event? is that the same thing as a handler?
i have a hard time understanding how events work, and what’s the best way to make my own event handler.
say i want to make a handler onImageDownloaded() that gets called when a certain event happens. like perhaps i’m downloading an image, and i want to trigger an event when the image downloads (and yes, i get that there is something called AsyncTask and also posting a runnable message from background thread, but for pedagogical reasons let’s pretend the process could have been on the UI thread also). How does Android know to call the method onImageDownloaded() ? or rather, how do i specify that when an image gets downloaded, i want it to call my method onImageDownloaded() ?
i’ve read about broadcast intents, but that seems more of a system level and kind of over-doing it.
I know that when you make a button in the view, you can do
final Button b = (Button) findViewById(R.id.mybutton);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d("MyActivity", "button is clicked");
}
});
and it’s almost like setting a “hook” to the button that calls the particular “onClick” when the click event happens.
in my particular case, how would i create a custom callback method upon actions “XYZ” ??
sorry for the long question, thanks for the patience to read and to try and understand it
We need to first learn what is callback:
Wickipedia: Callback
To make our code more re-useable and optimize, we need call back.
Let’s say: you have a
classwhich downloads data from the internet. If you want to make the class more re-useable, you will define aprotocol(anyclassconstruct) to whom it will inform. Later theclasseswhich conforms to that protocol (or implements that protocol)can use the downloaded data accordingly.Callbacks are made typically using
interfacekeyword, butabstract classor a simpleclasscan be used also.Here is simple illustration how to make and use our own callbacks.