我开发了一个应用程序来读取点类型的KML文件,然后使用Google Elevation API更新它们的高程。您可以看到它接收点的纬度和经度,并使用API密钥附加它以检索高程。因为我的KML文件有多个点,所以我使用ThreadPool读取纬度和长点,用密钥附加它,并将URL发送到Google Elevation API。这样的事情:
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 :(得分:0)
修改代码如下。
将HeightTask
更改为实施Callable界面。
准备可调用任务的集合并使用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
执行给定的任务,在完成所有任务后返回持有其状态和结果的Futures列表。对于返回列表的每个元素,Future.isDone()都为true。请注意,已完成的任务可能正常终止或通过抛出异常终止。