首页 > 解决方案 > 将 Volley 调用更改为 AsyncTask

问题描述

我想更改此功能以便能够等到完成,因为当我使用它通过 API 登录时,需要一些时间才能获得答案,我的应用程序现在说登录失败,因为它不等待答案。

我知道我需要将我的类更改为 extends AsyncTask,但我不知道如何将此函数更改为doInBackground(),因为在每个教程中它们doInBackground仅发送到 URL 并返回字符串,但我还需要发送到函数请求类型、正文和callbackID

private void createCall(int type, String url, JSONObject data, final int callback) {
    JsonObjectRequest jsonRequest = new JsonObjectRequest(type, url,data,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    Log.d("Response", response.toString());
                    try {
                        callback(response, callback);
                    } catch (Exception e){
                        Log.d("API callback error", e.getMessage());
                    }

                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.d("Error response", error.toString());
                }
            }
    );
    queue.add(jsonRequest);
}

我希望能够等到我从 api 调用中得到任何结果。

标签: android

解决方案


如果您想冻结 UI 线程直到响应返回,那么您可以使用进度对话框而不需要使用 asynctask 。在队列中添加请求对象后,启动进度对话框。

//add the request to the queue
queue.add(jsonRequest); 

//initialize the progress dialog and show it
progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Fetching The File....");
progressDialog.show();

然后在收到服务器的响应后关闭对话框。

@Override
    public void onResponse(String response) {
//after finishing all work
        progressDialog.dismiss();
    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        Log.e(“Volly Error”,”Error: ”+error.getLocalizedMessage());
        progressDialog.dismiss();
    }
});

推荐阅读