如何在循环中提出Volley
请求,直到特定响应到来?
package raju.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.skyfishjy.library.RippleBackgroun;
public class xxx extends AppCompatActivity {
int xi= 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_xxx);
StringRequest sr = new StringRequest("http://reju.pe.hu/test.php", new Response.Listener<String>() {
@Override
public void onResponse(String response) {
if (response.contains("1")){
xi=1;
}
Log.w("res",response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
while (xi==0){
try {
Thread.sleep(1000);
RequestQueue xx = Volley.newRequestQueue(this);
xx.add(sr);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
答案 0 :(得分:1)
在这里,我创建了一个名为runRequest的方法,该方法包含您在上面给出的代码。我对代码所做的唯一更改是我正在等待对请求的响应,检查它是否是特定的响应。如果它不是特定的响应,则再次调用runRequest方法,如果它是特定响应,则不执行任何操作。
public void runRequest() {
StringRequest sr = new StringRequest("http://reju.pe.hu/test.php", new Response.Listener<String>() {
@Override
public void onResponse(String response) {
if (response.contains("1")) {
//here comes the specific response
} else {
runRequest();
//re run the request
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue xx = Volley.newRequestQueue(this);
xx.add(sr);
}