Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
676 views
in Technique[技术] by (71.8m points)

android - OkHttp trigger callback in originated class after finishing network actions

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...