OkHttp trigger callback in originated class after finishing network actions

情到浓时终转凉″ 提交于 2020-01-06 20:57:39

问题


Here is the scenario: I have an Activity, named MainActivity, calling a OkHttp wrapper class, named NetworkManager to perform network post in background:

// 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());
}

Then, in the NetworkManager, I perform the POST action in asynchronous mode:

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());
        }
    }
}

What I'm trying to achieve is to call a function in MainActivity after network POST is successful or failed. How can I achieve this?


回答1:


You can create an interface with onFailure and onResponse then let YourActivity implement it. And, on NetworkManagertry to notify YourActivity using listener.

       // 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);
    }


来源:https://stackoverflow.com/questions/34193555/okhttp-trigger-callback-in-originated-class-after-finishing-network-actions

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!