Image metaphor:
When you go to a shop to buy something, it happens that the thing you want is not available, so you leave your phone number with the assistant. After a few days, the shop has the goods, the assistant calls you, and then you go to the shop to pick up the goods after receiving the phone call. In this example, your phone number is called a callback function. If you leave your phone number to the clerk, it's called a registration callback function. If there's something in the store later, it's called an event that triggers the callback Association. If the clerk calls you, it's called a call callback function. If you go to the store to pick up the goods, it's called a response callback event. (from Zhihu)
Benefits of callback:
Reduce code coupling, make code more flexible and concise
Step 1: define callback interface
/**
* Created by pengkv on 15/10/22.
* Network request callback interface
*/
public interface HttpCallBackListener {
void onFinish(String respose);
void onError(Exception e);
}
Step 2: define callback function (take interface as parameter)
/**
* Created by pengkv on 15/10/22.
* Network request tool class
*/
public class HttpUtil {
public static void requestData(final String urlStr, final HttpCallBackListener listener) {
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection connection = null;
try {
URL url = new URL(urlStr);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
connection.setDoInput(true);
connection.setDoOutput(true);
InputStream in = connection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
if (listener != null) {
//Call back the onFinish method
listener.onFinish(sb.toString());
}
} catch (Exception e) {
if (listener != null) {
//Callback onError method
listener.onError(e);
}
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
}).start();
}
}
Step 3: use callback method 1
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
HttpUtil.requestData("Requested URL", new HttpCallBackListener() {
@Override
public void onFinish(String respose) {
//Process request
}
@Override
public void onError(Exception e) {
//Handling exceptions
}
});
}
}
Step 3: use callback method 2
public class MainActivity extends AppCompatActivity implements HttpCallBackListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
HttpUtil.requestData("Requested URL", this);
}
@Override
public void onFinish(String respose) {
//Process request
}
@Override
public void onError(Exception e) {
//Handling exceptions
}
}