你不能使用asynctask。 Volley關心它。您可以使用回調來處理數據和用戶界面。 是這樣的:
public class LoginActivity extends SinglePaneActivity implements DownloadCallback {
//...
public void sendRequest(){
Downloader download = new Download(this);
downloader.download(userName, password);
progresbar.show();
}
public void requestFinish(){
progersbar.dismis();
//... continue
}
}
回調:
public interface DownloadCallback {
void requestFinish();
}
類下載
private RequestQueue requestQueue;
DownloadCallback mcallback;
public void Downloader(DownloadCallback callback){
mCallback = callback;
requestQueue = Volley.newRequestQueue(mContext);
initVolleyListeners();
}
private void initVolleyListeners() {
mSuccessListener = new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
mCallback.requestFinish();
}
};
mErrorListener = new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
mCallback.requestFinish();
}
};
public void download(String user, String pass){
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, createJson(user, pass), mSuccessListener , mErrorListener) {
//header for send JSON to server
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
};
requestQueue.add(jsonObjectRequest);
}
而且一分。不要在json中發送用戶名。你把它作爲參數在頭文件中發送。使用這個application/x-www-form-urlencoded
並設置傳遞一個用戶名作爲頭中的參數。
更新: 現在它會工作。對不起,我匆忙寫下了它。 Article about how callback work
Volley已經異步處理http調用。你爲什麼要加入AsyncTask? – Christine