形象比喻:
你到一个商店买东西,刚好你要的东西没有货,于是你在店员那里留下了你的电话,过了几天店里有货了,店员就打了你的电话,然后你接到电话后就到店里去取了货。在这个例子里,你的电话号码就叫回调函数,你把电话留给店员就叫登记回调函数,店里后来有货了叫做触发了回调关联的事件,店员给你打电话叫做调用回调函数,你到店里去取货叫做响应回调事件。(来自知乎)
回调的好处:
降低代码的耦合性,使代码更灵活、简洁
步骤一 :定义回调接口
/**
* Created by pengkv on 15/10/22.
* 网络请求回调接口
*/
public interface HttpCallBackListener {
void onFinish(String respose);
void onError(Exception e);
}
步骤二:定义回调函数(将接口作为参数)
/**
* Created by pengkv on 15/10/22.
* 网络请求工具类
*/
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) {
//回调onFinish方法
listener.onFinish(sb.toString());
}
} catch (Exception e) {
if (listener != null) {
//回调onError方法
listener.onError(e);
}
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
}).start();
}
}
步骤三:使用回调方法一
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
HttpUtil.requestData("请求的网址", new HttpCallBackListener() {
@Override
public void onFinish(String respose) {
//处理请求
}
@Override
public void onError(Exception e) {
//处理异常
}
});
}
}
步骤三:使用回调方法二
public class MainActivity extends AppCompatActivity implements HttpCallBackListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
HttpUtil.requestData("请求的网址", this);
}
@Override
public void onFinish(String respose) {
//处理请求
}
@Override
public void onError(Exception e) {
//处理异常
}
}