【问题标题】:OkHttp trigger callback in originated class after finishing network actions完成网络操作后,OkHttp 在原始类中触发回调
【发布时间】:2016-03-15 14:18:58
【问题描述】:

场景如下:我有一个名为MainActivity的Activity,调用一个名为NetworkManager的OkHttp包装类在后台执行网络发布:

// In MainActivity
NetworkManager manager = new NetworkManager();
try {
    manager.post("http://www.example.com/api/", reqObj); // reqObj is a JSONObject
} catch(IOException ioe) {
    Log.e(TAG, ioe.getMessage());
}

然后,在NetworkManager中,我以异步模式执行POST动作:

public class NetworkManager {
    static String TAG = "NetworkManager";
    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    OkHttpClient client = new OkHttpClient();

    void post(String url, JSONObject json) throws IOException {
        //RequestBody body = RequestBody.create(JSON, json);
        try {
            JSONArray array = json.getJSONArray("d");
            RequestBody body = new FormEncodingBuilder()
                    .add("m", json.getString("m"))
                    .add("d", array.toString())
                    .build();
            Request request = new Request.Builder()
                    .url(url)
                    .post(body)
                    .build();

            // Asynchronous Mode
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Request request, IOException e) {
                    Log.e(TAG, e.toString());
                    // what should I put here?
                }

                @Override
                public void onResponse(Response response) throws IOException {
                    Log.w(TAG, response.body().string());
                    // what should I put here?
                }
            });
        } catch (JSONException jsone) {
            Log.e(TAG, jsone.getMessage());
        }
    }
}

我想要实现的是在网络 POST 成功或失败后调用MainActivity 中的函数。我怎样才能做到这一点?

【问题讨论】:

标签: android okhttp


【解决方案1】:

您可以使用onFailureonResponse 创建一个接口,然后让YourActivity 实现它。并且,在NetworkManager尝试使用监听器通知YourActivity

       // MainActivity implements NetworkListener 
        NetworkManager manager = new NetworkManager();
        manager.setOnNetWorkListener(this);
        try {
            manager.post("http://www.example.com/api/", reqObj); // reqObj is a JSONObject
        } catch(IOException ioe) {
            Log.e(TAG, ioe.getMessage());
        }
        void onFailure(Request request, IOException e) {
             // call your activity methods
        }
        void onResponse(Response response) {
             // call your activity methods  
        }

        // ======NetworkManager class============
        public class NetworkManager {
            static String TAG = "NetworkManager";
            public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
            OkHttpClient client = new OkHttpClient();
            public NetworkListenerv listener;
            public void setOnNetWorkListener(NetworkListener listener) {
                this.listener = listener
            }
            // Asynchronous Mode
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Request request, IOException e) {
                    Log.e(TAG, e.toString());
                    // what should I put here?
                    if (listener != null) {
                        listener.onFailure(request, e);
                    }
                }

                @Override
                public void onResponse(Response response) throws IOException {
                    Log.w(TAG, response.body().string());
                    // what should I put here?
                     if (listener != null) {
                        listener.onResponse(response);
                    }
                }
            });

    // Your interface;
     public interface NetworkListener {
        void onFailure(Request request, IOException e);
        void onResponse(Response response);
    }

【讨论】:

  • 太棒了!我试试这个解决方案~
  • 如果您需要更改 UI,则无济于事。
  • @zevero 为什么不呢,只需使用 Main 线程调用您的 updateUI 方法
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-15
  • 2015-09-18
  • 2010-11-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-20
相关资源
最近更新 更多