在此处发帖之前,我已尝试对 GPS 问题进行研究。当我测试我的代码时,它一遍又一遍地重复相同的输出。在计时器上调用方法 gpsStart()
。精细和粗略位置权限已添加到 list 中。 appendLog()
方法将输出存储在文件中。
public void gpsStart() {
// Acquire a reference to the system Location Manager
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Toast.makeText(getApplicationContext(), "location changed",
// Toast.LENGTH_SHORT).show();
// Called when a new location is found by the network location
// provider.
appendLog("Lat: " + location.getLatitude() + "\nLng: "
+ location.getLongitude()+"\n");
text3.setText("Lat: " + location.getLatitude() + "\nLng: "
+ location.getLongitude());
}
public void onStatusChanged(String provider, int status,
Bundle extras) {
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
}
};
// Register the listener with the Location Manager to receive location
// updates
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 0, 0, locationListener);
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
}
最佳答案
您不能在计时器中调用gpsStart()
方法。我要说的是 Location Listener 是如何工作的
What is Location Listener?
Location Listener 是在您的当前位置发生变化时通知您的类。要接收位置更新,您必须使用 LocationManager 类注册 LocationListener 类。
When to register Location Listener?
这取决于您的应用程序的要求。例如,如果您想要位置监听器在 map 上显示当前位置,那么您应该在 Activity 的 onCreate()
或 onResume()
方法中注册位置监听器,并在 onPause()
或 onStop()
方法。如果您希望在应用程序未运行时接收位置信息,则可以使用服务来接收位置信息。
How to Register/Unregister Location Listener?
要注册 LocationListener,您首先需要 LocationManager 类的实例,您可以使用如下上下文获取该实例
LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
之后您将必须设置位置提供商。有两种经常使用的提供商。
- GPS 提供商
- 网络提供商
现在要向此位置提供者注册位置接收器,有一个 LocationManager 的方法 requestLocationUpdates
。在此方法中,第一个参数是提供者名称,第二个参数是请求位置更新的最短时间。第三个参数是请求位置更改的最小距离。最后一个参数是 locationListener。
在这里你可以如何使用这个方法
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, minTime, minDistance, locationListener);
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, minTime, minDistance, locationListener);
要取消注册位置更新,您可以使用以下方法
locationManager.removeUpdates(locationListener)
注意:正如您在问题中提到的那样,您正在计时器中调用方法 gpsStart
因此每次调用此方法时它都会添加位置监听器。所以所有听众正在触发您的新位置,因此您可能多次获得相同的位置。取而代之的是,您应该在 Activity 开始时调用此方法一次,并在 Activity 结束时取消注册此 locationListener。
希望你得到。 :D
尽情享受吧!
关于Android-相同的 GPS 位置重复而不更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12188794/