gpt4 book ai didi

java - 在 LocationOverlay 对象的 .runOnFirstFix() 方法中取消 Runnable

转载 作者:行者123 更新时间:2023-11-29 06:11:31 24 4
gpt4 key购买 nike

我有一个非常依赖 map 功能的应用程序。从第一个 Activity 开始,我调用 runOnFirstFix() 方法在找到用户位置后从数据库加载大量数据,但我也希望能够中断此 runnable 并停止当我切换 Activity 或用户按下按钮停止运行时,它正在执行。

myLocationOverlay.runOnFirstFix(new Runnable() {
public void run() {
mc.animateTo(myLocationOverlay.getMyLocation());
mc.setZoom(15);
userLatitude = myLocationOverlay.getMyLocation().getLatitudeE6();
userLongitude = myLocationOverlay.getMyLocation().getLongitudeE6();
userLocationAcquired = true;
loadMapData(); //Here the method is called for heavy data retrieval
}
});

我怎样才能停止这个 Runnable 中途执行?

最佳答案

您可以(并且可能应该)使用 AsyncTask

private class MapLoader extends AsyncTask<Void, Void, Data> {
@Override
protected Data doInBackground(Void... params) {
return loadMapData(); //Here the method is called for heavy data retrieval, make it return that Data
}
@Override
protected void onPostExecute(Data result) {
//do things with your mapview using the loaded Data (this is executed by the uithread)
}
}

然后用

替换你的其他代码
final MapLoader mapLoader = new MapLoader();
myLocationOverlay.runOnFirstFix(new Runnable() {
public void run() {
mc.animateTo(myLocationOverlay.getMyLocation());
mc.setZoom(15);
userLatitude = myLocationOverlay.getMyLocation().getLatitudeE6();
userLongitude = myLocationOverlay.getMyLocation().getLongitudeE6();
userLocationAcquired = true;
mapLoader.execute();
}
});

那么当您不再希望它完成时,您应该能够取消正在运行的任务

mapLoader.cancel(true);

我希望代码可以编译,我还没有测试过,但它应该可以工作:)

只需确保创建 MapLoader 的是 ui 线程

编辑:我认为您需要将 mapLoader.execute(); 调用包装在 runOnUiThread() 调用中才能使其正常工作,因为 runOnFirstFix() 可能会产生一个新线程

关于java - 在 LocationOverlay 对象的 .runOnFirstFix() 方法中取消 Runnable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6665798/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com