我正在開發一個快速響應非常重要的項目,並且基本上它所做的是獲取用戶的當前位置,獲取一堆(最多可以少得幾個人)本地存儲的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找到一種方便易辦法來加入階段,這是非常重要的,所以我放棄了它
我實際上是在尋找最近的(根據路線長度)latlong。 timelimit是我可能實際需要添加的內容,但由於我寧願等待幾秒鐘,並獲得更接近的位置,因此我認爲我們可以安全地假設問題的目的是不存在時間限制 – user2717954 2014-10-17 08:36:05