2017-09-07 42 views
0

我開發了一個應用程序來讀取點類型的KML文件,然後使用Google Elevation API更新其高程。正如你所看到的,它接收點的緯度和經度,並附加一個API鍵來檢索高程。因爲我的KML文件有多個點,我已經使用線程池來讀取lat和長點的,用鑰匙將其追加,並且將該網址發送給谷歌高程API.Something這樣的:完成Android線程池中的回調

ScheduledThreadPoolExecutor executor = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(CORE_NUMBERS + 1); 
    String providerURL = provider.getServiceURL(); 
    String providerKey = provider.getServiceAPIkey(); 

for (PointFeature p: points) { 

     String coordinate = p.getLatitude() + "," + p.getLongitude();  // get latitude and longitude of the feature 
     String url = providerURL + "locations=" + coordinate + providerKey; // creating the url of web service which contains coordinate 
     HeightTask task = new HeightTask(url, p);       // task of each points    
     executor.execute(task);  
     } 

的heightTask類是我從API解析JSON結果並獲取海拔並設置heithUpdate標誌的地方。這裏是摘錄:

public class HeightTask implements Runnable { 

private String url;  
private Feature feature; 

public HeightTask(String url, Feature f) { 

    this.feature = f; 
    this.url = url;  
} 

@Override 
public void run() { 

    if (feature instanceof PointFeature) { 

     float height = GoogleAPIJsonParser.parsePoint(HttpManager.getData(url)); 
     if (height != Float.NaN){ 

      feature.updateHeight(height); 
      feature.setHeightUpdated(true); 
      Log.d("elevationPoint",height+""); 
     } 
    } 
} 
} 

我需要的是一個回調,以知道圖層中所有點的高程是否已經更新。 threadPool中是否有任何模式,或只是遍歷所有點並檢查hieghtUpdate標誌?

回答

0

修改代碼如下。

  1. 更改您的HeightTask以實現Callable接口。

  2. 準備的可調用任務的收集和使用提交invokeAll()

    List<HeightTask > futureList = new ArrayList<HeightTask >(); 
    for (PointFeature p: points) { 
    
        String coordinate = p.getLatitude() + "," + p.getLongitude();  // get latitude and longitude of the feature 
        String url = providerURL + "locations=" + coordinate + providerKey; // creating the url of web service which contains coordinate 
        HeightTask task = new HeightTask(url, p);  
        futureList.add(taks);  
    } 
    executor.invokeAll(futureList); 
    

的invokeAll:

<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) 
         throws InterruptedException 

執行給定的任務,返回的Future列表保持自己的狀態和結果全部完成。 Future.isDone()對於返回列表的每個元素都是true。請注意,完成的任務可能正常結束或通過拋出異常終止。