2014-10-17 56 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