接口回调

2016-08-11  本文已影响48人  Longmaxie

知乎大神:
你到一个商店买东西,刚好你要的东西没有货,于是你在店员那里留下了你的电话,过了几天店里有货了,店员就打了你的电话,然后你接到电话后就到店里去取了货。
在这个例子里,你的电话号码就叫回调函数,
你把电话留给店员就叫登记回调函数,
店里后来有货了叫做触发了回调关联的事件,
店员给你打电话叫做调用回调函数,
你到店里去取货叫做响应回调事件。

好处: 降低代码的耦合性,使代码更灵活、简洁
用法:
1.定义回调接口:

/** 
   * 网络请求回调接口 
 */
public interface HttpCallBackListener { 
          void onFinish(String respose); 
          void onError(Exception e);
}
  1. 定义回调函数(将接口作为参数)
// 网络请求工具类
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(); }}
  1. 使用回调方法
onCreate() {
 HttpUtil.requestData("请求的网址", new HttpCallBackListener() { 
 @Override 
 public void onFinish(String respose) { //处理请求 } 
 @Override 
 public void onError(Exception e) { //处理异常 } });
}
  1. 使用回调方法2
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) { //处理异常 }}
上一篇下一篇

猜你喜欢

热点阅读