gpt4 book ai didi

Android - 可靠地获取当前位置

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:07:29 27 4
gpt4 key购买 nike

我的应用会在特定时间检查用户是否在给定位置。我使用警报管理器启动一个服务来进行此调用:

locationManager.requestLocationUpdates(bestProvider, 0, 0, listener);

同时检查:

 locationManager.getLastKnownLocation(bestProvider);

但是我在真实设备上运行时遇到了问题。一方面,getLastKnownLocation 很可能是 GPS 的最后一个位置,它可能在任何地方(即,它可能距离用户当前位置数英里)。所以我将等待 requestLocationUpdates 回调,如果它们在两分钟内不存在,则移除监听器并放弃,对吗?

错误,因为如果用户的位置已经稳定(即,他们最近使用了 GPS 并且没有移动过),那么我的监听器将永远不会被调用,因为位置不会改变。但是 GPS 会一直运行,直到我的监听器被移除,耗尽电池...

获取当前位置而不会将旧位置误认为当前位置的正确方法是什么?我不介意等几分钟。

编辑:有可能我对没有调用监听器的看法是错误的,它可能比我想象的要花更长的时间......很难说。我仍然希望得到明确的答复。

最佳答案

代码可能是这样的:

public class MyLocation {
Timer timer1;
LocationManager lm;

public boolean getLocation(Context context)
{
lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListenerGps);
timer1=new Timer();
timer1.schedule(new GetLastLocation(), 20000);
return true;
}

LocationListener locationListenerGps = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
lm.removeUpdates(this);
//use location as it is the latest value
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};

class GetLastLocation extends TimerTask {
@Override
public void run() {
lm.removeUpdates(locationListenerGps);
Location location=lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
//use location as we have not received the new value from listener
}
}
}

我们启动监听器并等待更新一段时间(在我的示例中为 20 秒)。如果我们在此期间收到更新,我们将使用它。如果我们在这段时间内没有收到更新,我们将使用 getLastKnownLocation 值并停止监听器。

你可以在这里看到我的完整代码 What is the simplest and most robust way to get the user's current location on Android?

编辑(提问者):这是大部分答案,但我的最终解决方案使用 Handler 而不是 Timer。

关于Android - 可靠地获取当前位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3120256/

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