我无法让 RequestFuture 工作,所以我只使用了 Makibo 建议的回调监听器。我不知道他为什么被否决,这可能是解决不同 Volley 请求的原始常见问题的最佳解决方案,这些请求都取决于初始登录或其他内容。在这个例子中,我想上传一张照片,但首先我要检查用户是否登录。如果没有,我必须登录,然后在上传照片之前等待成功。如果已经登录,直接上传照片。
这是我的示例代码:
// interface we'll use for listener
public interface OnLoginListener {
public void onLogin();
}
public void uploadPhoto(final String username, final String password, final String photo_location) {
// first setup callback listener that will be called if/when user is logged in
OnLoginListener onLoginListener=new OnLoginListener() {
@Override
public void onLogin() {
uploadPhotoLoggedIn(photo_location);
}
};
// simplistic already logged in check for this example, just checking if username is null
if (loggedInUsername==null) {
// if it null, login and pass listener
httpLogin(username, password, onLoginListener);
} else {
// if not null, already logged in so just call listener method
onLoginListener.onLogin();
}
}
public void httpLogin(String username, String password, final OnLoginListener onLoginListener) {
StringRequest loginRequest = new StringRequest(Request.Method.POST, "https://www.example.com/login.php", new Response.Listener<String>() {
@Override
public void onResponse(String txtResponse) {
Log.d("STACKOVERFLOW",txtResponse);
// call method of listener after login is successful. so uploadPhotoLoggedIn will be called now
onLoginListener.onLogin();
} },
new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
Log.d("VOLLEYERROR","error => "+error.toString());
}
}
) {
};
// Just getting the Volley request queue from my application class (GetApplicatio.java), and adding request
GetApplication.getRequestQueue().add(loginRequest);
}