2014-10-17 15 views
1

我正在开发一个快速响应非常重要的项目,并且基本上它所做的是获取用户的当前位置,获取一堆(最多可以少得几个人)本地存储的LatLng对象,并请求google web api获取路线。Android - 发送很多请求的正确方式

我的问题是 - 什么是做1)正确的方式; 2)不采取年龄完成(假定一个像样的网络连接)

现在我把路径 - 创建一个线程每个请求和更新一些数据结构,当所有线程完成,继续评估

这是basicly我的代码:

private class RetrieveTracks extends AsyncTask<Void, Void, Data> { 

    private Data data; 

    @Override 
    protected Data doInBackground(Void... params) { 
     data = new Data(); 
     List<Thread> threads = new ArrayList<Thread>(); 
     for (LatLng lat : lats) { //lats is some collection with the LatLng objects I got 
       Thread thread = new Thread(new DirectionsFinder(lat, data, currentLocation)); 
       threads.add(thread); 
       thread.start(); 
     } 
     for (Thread thread : threads) { 
      try { 
       thread.join(); 
      } catch (InterruptedException e) { 
       e.printStackTrace(); 
      } 
     } 
     return data; 
    } 
    @Override 
    protected void onPostExecute(Data data) { 
     //update map with Data 
    } 
} 

public class DirectionsFinder implements Runnable { 

    private LatLng lat; 
    private Data data; 
    private LatLng curLoc; 


    public DirectionsFinder(Latlng lat, Data data, LatLng curLoc) { 
    this.lat = lat; 
    this.data = data; 
    this.curLoc = curLoc; 
    } 

    @Override 
    public void run() { 
     //send GET request to google web api and get the directions 
     synchronized (data) { 
      //update data 
     } 
    } 
    } 

也侧面的问题,我得到了 - 在某些情况下我可能会在中期的执行足够的数据,使我不再ne编辑来获取信息,有没有办法从正在运行的线程中“休息”出来?

起初,我试图用可赎回和FutureTask对我试图要做什么,但coulnd't找到一种方便易办法来加入阶段,这是非常重要的,所以我放弃了它

回答

0

我会假设你在轨道检索之后继续进行之前,理想的情况是希望谷歌在所有方向上响应来自Google的方向响应?你的情况听起来很典型,因为说快递员有10个小包要送到镇上去,并且想要确定最有效的交付方案。然后尝试单独获取所有目的地的驾车路线有助于计算。每次调用Google结果最终都会收到一次旅行的方向,并且总的响应时间会加总几次。您可能需要确定一些时间限制等待每个响应的时间。我不确定您是否准备放弃或重试缓慢的响应请求。如果您在设备上运行应用程序时处于移动状态,则可能无法保证所有请求的体面响应时间。这不是一个确凿的答案,但您的回答可以帮助社区提出更准确的建议。

+0

我实际上是在寻找最近的(根据路线长度)latlong。 timelimit是我可能实际需要添加的内容,但由于我宁愿等待几秒钟,并获得更接近的位置,因此我认为我们可以安全地假设问题的目的是不存在时间限制 – user2717954 2014-10-17 08:36:05