How to manage the various tasks that AsyncTask needs to call

I have an external library to use that communicates with the server over the Internet. Every time I need to get information from the Internet, the android makes me use asynthesis. There are no problems so far. However, I am getting more and more tasks of extracting (in different ways) data from the Internet, and I do not like the increase in different classes for each individual call. In short: I have different Internet calls, and instead of creating an synthetics class for each call, I would prefer one class to handle all the different calls. Is it possible? And more importantly, what is the right way to do this?

+4
source share
2 answers

I also had a problem with a similer like yours. But I solved this problem with Reflection Technique. I made a method to prevent the increase of different classes in order to cause a single blow. I made a single asynthesis class and passed the functionName and activity context and returned an onPostExecute response.

Here is an example -

AsyncTaskConnection.java

public class AsyncTaskConnection extends AsyncTask<String, String, Object>{
    JSONObject mainObject;
    Context mContext;
    String returnFunctionName;

    public AsyncTaskConnection (Context context){
         mContext = context;
    }

    protected void onPreExecute() {
        // preExecute
    }

    @Override
    protected Object doInBackground(String... arguments) {
        String apiFunctionName = arguments[0]; // get api FunctionName 
        String jsonString = arguments[1]; // get data
        returnFunctionName = apiFunctionName+"Response"; // return function name
        // some connection code...


        //then call...
            try {
                ht.call(NAMESPACE, requestEnvelop);
            } catch (IOException ex) {
                Log.d(mContext.getClass().getName(), "Io exception bufferedIOStream closed" + ex);
                ex.printStackTrace();
            }
            return mainObject.toString();
        } catch (Exception e) {
            Log.d("Exception", e.toString());
            return "no";
        }
    }

    // main thing is there, i have use the reflaction here....

    @Override
    protected void onPostExecute(Object backresult) {
        Method m;
        try {

            m = mContext.getClass().getDeclaredMethod(returnFunctionName, String.class);
            m.invoke(mContext, (String) backresult);
        } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }

in caller class

//call this class where you want and get dynamic response 
new AsyncTaskConnection(this).execute("getHomepage",jo.toString());

// and make response fuction

protected void getHomepageResponse(String backresult) {
            try {
// this is your response
                mainObject = new JSONObject(backresult);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

And there can be many ways to get the result you want.

+1
source

Yes, it is possible, but you need to create some common AsyncTask that accepts an API (url to call) and a handler when receiving the result.

Async Class:

public class AsyncTaskThread extends AsyncTask<Object, Object, Object> {
    //instance variables
    Handler myHandler;
    public AsyncTaskThread(String uriString, Handler myHandler) {
       //set these arguments to respective instance variables 
       this.myHandler=myHandler;
    }
      protected Object doInBackground(Object... obj){
          //business  logic
      }
    //----implement other  methods of Async as per your requirement
      @Override
    protected void onPostExecute(Object result) {
          super.onPostExecute(result);
          Message message = new Message();
          message.obj = result;
          myHandler.sendMessage(message);
}

}

Skip the handler for the stream:
You need to pass the handler above the Async task in the argument.

new AsyncTaskThread(uri,new MyHandler())

import android.os.Handler;
private class MyHandler extends Handler{
        @Override
        public void handleMessage(Message msg) {
            Model response = (Model) msg.obj;
        }
}

sendMessage() async.

:
okhttp API, . https://github.com/square/okhttp/wiki/Recipes

+1

Source: https://habr.com/ru/post/1619630/


All Articles