Android 使用回调接口实现异步任务-在单个回调接口中处理多个调用响应

Android 使用回调接口实现异步任务-在单个回调接口中处理多个调用响应,android,android-asynctask,Android,Android Asynctask,在我的Android应用程序中,我从一个活动中调用多个API。我使用以下方法:在活动中实现接口,并从异步类调用该接口函数 public interface AsyncResponse { public void processFinish(JSONObject sb); } public class FetchData extends AsyncTask<String, Integer, JSONObject> { HttpURLConnection urlCon

在我的Android应用程序中,我从一个活动中调用多个API。我使用以下方法:在活动中实现接口,并从异步类调用该接口函数

public interface AsyncResponse {
    public void processFinish(JSONObject sb);
}


public class FetchData extends AsyncTask<String, Integer, JSONObject> {
    HttpURLConnection urlConnection;
    String url;
    String method;
    String payload = null;
    AsyncResponse delegate = null;

    public FetchData(AsyncResponse delegate, String url, String method) {
        this.delegate = delegate;
        this.url = url;
        this.method = method;
    }

    public FetchData(AsyncResponse delegate, String url, String method, JSONObject payload) {
        this(delegate, url, method);
        this.payload = payload.toString();
    }

    @Override
    protected JSONObject doInBackground(String... args) {
        BufferedReader reader = null;

        try {
            URL url = new URL(this.url);

            // Open HTTP connection
            urlConnection = (HttpURLConnection) url.openConnection();

            // HTTP method GET/POST/PUT/DELETE
            urlConnection.setRequestMethod(this.method); 

            // handle issues
            int statusCode = urlConnection.getResponseCode();

            // Get the response
            InputStream inputStream = urlConnection.getInputStream();
            if(inputStream == null) {
                // Nothing to do
                return null;
            }
            reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
            String inputLine = null;
            StringBuffer response = new StringBuffer();

            while ((inputLine = reader.readLine()) != null) {
                response.append(inputLine + "\n");
            }

            return new JSONObject(response.toString());
        } catch(Exception e) {
            try {
                // Return error response
            } catch(Exception e1) {
                System.out.println(e1);
                return null;
            }
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (final IOException e) {
                    Log.e("PlaceholderFragment", "Error closing stream", e);
                }
            }
        }
    }

    @Override
    protected void onPostExecute(JSONObject result) {
        super.onPostExecute(result);
        this.delegate.processFinish(result);
    }
}


public class AsyncTasks extends AppCompatActivity implements AsyncResponse {
    TextView view = null;
    int a = 1;
    Utility utility = Utility.getInstance();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_async_tasks);
        new FetchData(this, "<url 1>", "GET").executeOnExecutor(THREAD_POOL_EXECUTOR);

        new FetchData(this, "<url 2>", "GET").executeOnExecutor(THREAD_POOL_EXECUTOR);
    }

    @Override
    public void processFinish(JSONObject data) {
        utility.showDialog(this, data.toString());
    }
}
公共接口异步响应{
公共无效处理完成(JSONObject sb);
}
公共类FetchData扩展异步任务{
HttpURLConnection-urlConnection;
字符串url;
字符串方法;
字符串有效负载=null;
AsyncResponse委托=null;
公共FetchData(异步响应委托、字符串url、字符串方法){
this.delegate=委托;
this.url=url;
这个方法=方法;
}
公共FetchData(异步响应委托、字符串url、字符串方法、JSONObject负载){
这(委托、url、方法);
this.payload=payload.toString();
}
@凌驾
受保护的JSONObject doInBackground(字符串…args){
BufferedReader reader=null;
试一试{
URL=新URL(this.URL);
//打开HTTP连接
urlConnection=(HttpURLConnection)url.openConnection();
//HTTP方法GET/POST/PUT/DELETE
urlConnection.setRequestMethod(this.method);
//处理问题
int statusCode=urlConnection.getResponseCode();
//得到回应
InputStream InputStream=urlConnection.getInputStream();
如果(inputStream==null){
//无事可做
返回null;
}
reader=新的BufferedReader(新的InputStreamReader(inputStream,“UTF-8”));
字符串inputLine=null;
StringBuffer响应=新的StringBuffer();
而((inputLine=reader.readLine())!=null){
响应。追加(inputLine+“\n”);
}
返回新的JSONObject(response.toString());
}捕获(例外e){
试一试{
//返回错误响应
}捕获(异常e1){
系统输出打印LN(e1);
返回null;
}
}最后{
if(urlConnection!=null){
urlConnection.disconnect();
}
if(读卡器!=null){
试一试{
reader.close();
}捕获(最终IOE例外){
Log.e(“占位符片段”,“错误关闭流”,e);
}
}
}
}
@凌驾
受保护的void onPostExecute(JSONObject结果){
super.onPostExecute(结果);
this.delegate.processFinish(结果);
}
}
公共类AsyncTasks扩展AppCompatActivity实现AsyncResponse{
TextView=null;
INTA=1;
Utility=Utility.getInstance();
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity\u async\u tasks);
新的FetchData(this,,“GET”).executeOnExecutor(线程池执行器);
新的FetchData(this,,“GET”).executeOnExecutor(线程池执行器);
}
@凌驾
公共void processFinish(JSONObject数据){
utility.showDialog(this,data.toString());
}
}
这里如何在processFinish()接口函数中处理第二个GET调用的响应?最好的方法是什么?

公共接口异步响应{
public interface AsyncResponse {
    //Add requestCode to identify request.  
    public void processFinish(JSONObject sb, int requestCode);
}


public class FetchData extends AsyncTask<String, Integer, JSONObject> {
    HttpURLConnection urlConnection;
    String url;
    String method;
    String payload = null;
    AsyncResponse delegate = null;
    int requestCode;

    public FetchData(String url, String method) {
        this(url, method, null);
    }

    public FetchData(String url, String method, JSONObject payload) {
        this.url = url;
        this.method = method;
        if(payload!=null){
             this.payload = payload.toString();
        }
    }

    //You can set AsyncResponse and RequestCode in constructor also.
    public FetchData setListener(AsyncResponse asyncResponse, int requestCode){
        this.delegate = asyncResponse;
        this.requestCode = requestCode;
        return this;
    }

    @Override
    protected JSONObject doInBackground(String... args) {
        ....
    }

    @Override
    protected void onPostExecute(JSONObject result) {
        super.onPostExecute(result);
        if(delegate!=null){        
            //post result with given requestCode
            this.delegate.processFinish(result, requestCode);
        }
    }
}


public class AsyncTasks extends AppCompatActivity implements AsyncResponse {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_async_tasks);

        // Make first call with request code as 1    
        new FetchData("<url 1>", "GET").setListener(this, 1).executeOnExecutor(THREAD_POOL_EXECUTOR);

        // Make second call with request code as 2
        new FetchData("<url 2>", "GET").setListener(this, 2).executeOnExecutor(THREAD_POOL_EXECUTOR);
    }

    @Override
    public void processFinish(JSONObject data, int requestCode) {
        switch(requestCode){
            case 1:
            //perform task on 1st call finish
            break;
            case 2:
            utility.showDialog(this, data.toString());
            //perform task on 2nd call finish
            break;
        }
    }
}
//添加requestCode以标识请求。 公共void processFinish(JSONObject sb,int requestCode); } 公共类FetchData扩展异步任务{ HttpURLConnection-urlConnection; 字符串url; 字符串方法; 字符串有效负载=null; AsyncResponse委托=null; int请求码; 公共获取数据(字符串url、字符串方法){ 这个(url、方法、null); } 公共获取数据(字符串url、字符串方法、JSONObject负载){ this.url=url; 这个方法=方法; 如果(有效负载!=null){ this.payload=payload.toString(); } } //您还可以在构造函数中设置AsyncResponse和RequestCode。 公共FetchData setListener(AsyncResponse AsyncResponse,int requestCode){ this.delegate=asyncResponse; this.requestCode=requestCode; 归还这个; } @凌驾 受保护的JSONObject doInBackground(字符串…args){ .... } @凌驾 受保护的void onPostExecute(JSONObject结果){ super.onPostExecute(结果); 如果(委托!=null){ //使用给定的请求代码发布结果 this.delegate.processFinish(结果、请求代码); } } } 公共类AsyncTasks扩展AppCompatActivity实现AsyncResponse{ @凌驾 创建时受保护的void(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity\u async\u tasks); //使用请求代码1进行第一次呼叫 新的FetchData(“,”GET“).setListener(this,1).executeOnExecutor(线程池执行器); //进行第二次呼叫,请求代码为2 新的FetchData(“,”GET“).setListener(this,2).executeOnExecutor(线程池执行器); } @凌驾 公共void processFinish(JSONObject数据,int请求代码){ 开关(请求代码){ 案例1: //在第一次呼叫完成时执行任务 打破 案例2: utility.showDialog(this,data.toString()); //在第二次呼叫完成时执行任务 打破 } } }
也许我晚了一点。 但是我和你面临着同样的问题,验证答案中的这个切换案例让我非常恼火,所以在这里,你可以找到一种方法,使用匿名异步响应实现任意多的请求

在中,当您传递AsyncTasks类以通过实现管理回调时,将获取数据
public interface AsyncResponse {
    //Add requestCode to identify request.  
    public void processFinish(JSONObject sb, int requestCode);
}


public class FetchData extends AsyncTask<String, Integer, JSONObject> {
    HttpURLConnection urlConnection;
    String url;
    String method;
    String payload = null;
    AsyncResponse delegate = null;
    int requestCode;

public FetchData(String url, String method) {
    this(url, method, null);
}

public FetchData(String url, String method, JSONObject payload) {
    this.url = url;
    this.method = method;
    if(payload!=null){
         this.payload = payload.toString();
    }
}

//You can set AsyncResponse and RequestCode in constructor also.
public FetchData setListener(AsyncResponse asyncResponse, int requestCode){
    this.delegate = asyncResponse;
    this.requestCode = requestCode;
    return this;
}

@Override
protected JSONObject doInBackground(String... args) {
    ....
}

@Override
protected void onPostExecute(JSONObject result) {
    super.onPostExecute(result);
        if(delegate!=null){        
            //post result with given requestCode
            this.delegate.processFinish(result, requestCode);
        }
    }
}


public class AsyncTasks extends AppCompatActivity{

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_async_tasks);

    // Make first call with request code as 1. Use anonym callBack implementation
    new FetchData("<url 1>", "GET").setListener(new AsyncResponse () {
            @Override
            public void processFinish(JSONObject sb, int requestCode) {
                //perform task on 1st call finish
            }
        }, 1).executeOnExecutor(THREAD_POOL_EXECUTOR);

    // Make second call with request code as 2
    new FetchData("<url 2>", "GET").setListener(new AsyncResponse () {
            @Override
            public void processFinish(JSONObject sb, int requestCode) {
                //perform task on 2st call finish
            }
        }, 2).executeOnExecutor(THREAD_POOL_EXECUTOR);

    // Make as many call to FetchData and implement an anonym AsyncResponse each time

}