如何确定GPS位置是否已在android上获取?
比方说,我有一个按钮,只有当系统知道EXACT用户的位置时,才会调用另一个活动。我做了一个对话框,要求用户在禁用GPS时打开GPS,但是当用户启用GPS并再次按下按钮时,我可能还没有确切的位置。谁能帮我这个 ?如何确定GPS位置是否已在android上获取?
您需要创建一个LocationListener并等待回调。它在API docs很好描述:
// 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) {
// When you get here you have a location...
useTheNewLocationToEnableTheButton(location);
}
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);
如果你不知道坐标,最好的办法是在检索一个位置时显示一个ProgressDialog
,当你得到它时,关闭ProgressDialog并启动你的活动。
final LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
//here you can get coordinates via location.getLongitude() and
//location.getLatitude() methods, dismiss the progress dialog and
//start your activity
locationManager.removeUpdates(this);
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
您可以侦听GpsStatus事件,以确保用户实际启用GPS(GPS_EVENT_STARTED),并且当GPS获得位置定位通知(GPS_EVENT_FIRST_FIX)。
对于GPS_EVENT_FIRST_FIX事件为+1。我不知道这个,非常有用。唯一的问题是,如果您在室内或无法以某种方式接收到良好的GPS信号,您可能会等待很长时间才能发生此事件。 – 2011-05-04 21:13:53
在这种情况下,你应该有一些超时:如果gps修复不是在一定的时间内获得的,而是通知用户这一点。 – 2011-05-04 21:18:23
请更好地解释你的问题的最后部分..需要更多的说明。 – JoxTraex 2011-05-04 20:33:15