java 回撥的基本使用,HttpUtil邏輯封裝
阿新 • • 發佈:2018-12-16
回撥 邏輯圖
HttpCallbackListener 介面,也就是 耗時操作結束後返回給 呼叫方 的通道
public interface HttpCallbackListener {
void onFinished(String response);
void onError(Exception e);
}
HttpUtil 耗時操作在這裡進行
public class HttpUtil { public static void sendHttpRequest(String address, final HttpCallbackListener callbackListener) { new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(5000); callbackListener.onFinished("請求完成"); Thread.sleep(5000); callbackListener.onError(new Exception()); } catch (InterruptedException e) { e.printStackTrace(); } } }).start(); } }
MainActivity.java
public void callbackTest(View view) { HttpUtil.sendHttpRequest("http://www.baidu.com", new HttpCallbackListener() { @Override public void onFinished(String response) { Log.i(TAG, "請求成功: "+response); // 列印結果 } @Override public void onError(Exception e) { Log.i(TAG, "請求失敗: "); } }); }