如何确定是否已在Android上获得GPS位置?

时间:2011-05-04 20:25:50

标签: android gps

假设我有一个按钮,只有在系统知道EXACT用户的位置时才调用另一个活动。我做了一个对话框,要求用户打开GPS,如果它被禁用,但当用户启用GPS并再次按下按钮时,我可能还没有确切的位置。任何人都可以帮我这个吗?

3 个答案:

答案 0 :(得分:3)

您需要创建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);

答案 1 :(得分:1)

您可以收听GpsStatus个事件,以确保用户实际启用了GPS(GPS_EVENT_STARTED),并在GPS获得定位时收到通知(GPS_EVENT_FIRST_FIX)。

答案 2 :(得分:0)

如果您不知道坐标,最好的方法是在检索位置时显示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);