Android Volley请求同步问题

时间:2017-01-19 03:37:29

标签: android multithreading loops android-volley

我有一个在服务中运行的处理程序。在处理程序内部,我运行两个for循环。

在第一个for循环中,我从数据库中获取一些数据,并在每次迭代时生成一些排序请求。这些齐射请求的响应会更改存储在文件系统中的某些文件以及某些数据库更改。第二个for循环需要处理第一个循环中这些请求所做的更改。为此,第二个for循环需要等待第一个循环所做的更改请求。但是,第一个循环中的请求需要更多时间才能完成。第二个for循环在进行这些更改之前运行,因此没有新的请求由第二个for循环进行,因为没有收到任何数据更改。

如何等待第二个for循环直到第一个for循环的所有请求都完成?

private final class Handler extends Handler {
  public Handler(Looper looper) {
    super(looper);
  }

  @Override
  public void handleMessage(Message msg) {
        //1st for loop
    for (do some database processing) {
      volleyrequestclass.make a volley request....the response from this volleyrequest make certain changes to database and filesystem
    }

    //2nd for loop ...this needs to wait till all requests from loop1 are successfully completed
    for(process on changes made by request in loop1)
    {
    make a volley request based on changes made by requests in first loop
    }
  }
}

1 个答案:

答案 0 :(得分:1)

一种解决方案是使用RequesFuture

//1st for loop 
for (do some database processing) {

  RequestFuture<String> future = RequestFuture.newFuture(); 
  StringRequest stringRequest = new StringRequest(Request.Method.GET, url, future, future);
  RestPlatform.getInstance(Application.instance).getRequestQueue().add(stringRequest);
 future.get();
}

此解决方案可以阻止您执行并行请求。 另一种解决方案可以是:

//n is number of times loop will be running. 
final CountDownLatch signal = new CountDownLatch(n);
//Volley Request
//In listener or onResponse do 
signal.countdown();

   //1st for loop 
for (do some database processing) {
  volleyrequestclass.make a volley request....the response from this volleyrequest make certain changes to database and filesystem 
} 
 // here you need to await untill your countdown is not zero. 
try {
  signal.await();// wait for callback
} catch (InterruptedException e) {
  throwTestEvironmentException(e);
}
//2nd for loop ...this needs to wait till all requests from loop1 are successfully completed 
for(process on changes made by request in loop1) 
{ 
make a volley request based on changes made by requests in first loop 
} 

所以这些是可以有效运作的两种解决方案。

相关问题