当我试图获取当前用户的位置时,我总是在android中得到latitude = 0和longitude = 0的值。如何解决?

时间:2016-06-09 01:58:03

标签: android google-maps android-studio gps

在Android API级别23中使用GPS实现LocationListener并获取最后知道位置的类。此类包括获取当前用户的纬度和经度的函数。

public class Teacher_Location extends Service implements LocationListener {

private final Context mContext;

// flag for GPS status
boolean isGPSEnabled = false;

// flag for network status
boolean isNetworkEnabled = false;

// flag for GPS status
boolean canGetLocation = false;

Location location; // location
double latitude; // latitude
double longitude; // longitude

// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 0; // 10 meters

// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES =0; // 1 minute

// Declaring a Location Manager
protected LocationManager locationManager;

public Teacher_Location(Context context) {
    this.mContext = context;
    getLocation();
}

public Location getLocation() {
    try {
        locationManager = (LocationManager) mContext
                .getSystemService(LOCATION_SERVICE);

        // getting GPS status
        isGPSEnabled = locationManager
                .isProviderEnabled(LocationManager.GPS_PROVIDER);

        // getting network status

        if (!isGPSEnabled) {
            // no network provider is enabled
        } else {
            this.canGetLocation = true;
            // if GPS Enabled get lat/long using GPS Services
            if (isGPSEnabled) {
                if (location == null) {
                 if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
                        locationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    }

                    Log.d("GPS Enabled", "GPS Enabled");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return location;
}

/**
 * Stop using GPS listener
 * Calling this function will stop using GPS in your app
 * */
public void stopUsingGPS(){
    if(locationManager != null){
        locationManager.removeUpdates(Teacher_Location.this);
    }
}

/**
 * Function to get latitude
 * */
public double getLatitude(){
    if(location != null){
        latitude = location.getLatitude();
    }

    // return latitude
    return latitude;
}

/**
 * Function to get longitude
 * */
public double getLongitude(){
    if(location != null){
        longitude = location.getLongitude();
    }

    // return longitude
    return longitude;
}

/**
 * Function to check GPS/wifi enabled
 * @return boolean
 * */
public boolean canGetLocation() {
    return this.canGetLocation;
}

/**
 * Function to show settings alert dialog
 * On pressing Settings button will lauch Settings Options
 * */
public void showSettingsAlert(){
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

    // Setting Dialog Title
    alertDialog.setTitle("GPS is settings");

    // Setting Dialog Message
    alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

    // On pressing Settings button
    alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog,int which) {
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            mContext.startActivity(intent);
        }
    });

    // on pressing cancel button
    alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
        }
    });

    // Showing Alert Message
    alertDialog.show();
}

@Override
public void onLocationChanged(Location loc) {
   this.location=loc;
}

@Override
public void onProviderDisabled(String provider) {
    showSettingsAlert();
}

@Override
public void onProviderEnabled(String provider) {

}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}

@Override
public IBinder onBind(Intent arg0) {
    return null;
}

}

这是从实现LocationListener的类Teacher_Location中获取纬度和经度的代码。

teacher_location=new Teacher_Location(this);
        if(teacher_location.canGetLocation())
        {
            double latitude = teacher_location.getLatitude();
            double longitude = teacher_location.getLongitude();

            // \n is for new line
            Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
            teacher_location.stopUsingGPS();
        }
        else
        {
            teacher_location.showSettingsAlert();
        }
  

在我的情况下,这显示了纬度= 0和经度= 0。教我   如何在android studio中获取当前的经纬度。   click here to view screen shot of my activity

3 个答案:

答案 0 :(得分:2)

位置管理器异步执行它的工作 - 这就是你需要一个监听器的原因。

您实例化了Teacher_Location类,而该类又开始侦听位置,并立即从中请求该位置(但尚未找到您的位置)。

基本上,您尝试从位置对象中读取值,然后才能获取更新的位置,从而为经度和纬度返回0(默认值)。

相反,您需要在onLocationChanged(位置位置)方法中侦听位置更改。它将通知您新的位置更新,并根据您可以执行其他操作。

这里的关键是它是异步的,您必须等待侦听器回调提供给您的数据。

答案 1 :(得分:0)

您可以使用以下代码示例开始。

       public class CurrentLocation {
          Timer timer;
          LocationManager locationManager;
          LocationResult locationResult;
          boolean gpsEnabled=false;
          boolean networkEnabled=false;

      public boolean getLocation(Context context, LocationResult result)
          {
          //I use LocationResult callback class to pass location value from MyLocation to user code.
          locationResult=result;
          if(locationManager ==null)
             locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

        //exceptions will be thrown if provider is not permitted.
       try{
          gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);}catch(Exception ex){}
        try{
         networkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);}catch(Exception ex){}

       //don't start listeners if no provider is enabled
      if(!gpsEnabled && !networkEnabled)
         return false;

      if(gpsEnabled)
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListenerGps);
     if(networkEnabled)
       locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListenerNetwork);
    timer =new Timer();
    timer.schedule(new GetLastLocation(), 20000);
   return true;
}

    LocationListener locationListenerGps = new LocationListener() {
public void onLocationChanged(Location location) {
    timer.cancel();
    locationResult.gotLocation(location);
    locationManager.removeUpdates(this);
    locationManager.removeUpdates(locationListenerNetwork);
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras)   {}
};

LocationListener locationListenerNetwork = new LocationListener() {
  public void onLocationChanged(Location location) {
    timer.cancel();
    locationResult.gotLocation(location);
    locationManager.removeUpdates(this);
    locationManager.removeUpdates(locationListenerGps);
}
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() {
    locationManager.removeUpdates(locationListenerGps);
    locationManager.removeUpdates(locationListenerNetwork);

    Location net_loc=null, gps_loc=null;
    if(gpsEnabled)
        gps_loc= locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    if(networkEnabled)
        net_loc= locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

    //if there are both values use the latest one
    if(gps_loc!=null && net_loc!=null){
        if(gps_loc.getTime()>net_loc.getTime())
            locationResult.gotLocation(gps_loc);
        else
            locationResult.gotLocation(net_loc);
        return;
    }

    if(gps_loc!=null){
        locationResult.gotLocation(gps_loc);
        return;
    }
    if(net_loc!=null){
        locationResult.gotLocation(net_loc);
        return;
    }
    locationResult.gotLocation(null);
}
 }

public void cancelTimer() {
   timer.cancel();
    locationManager.removeUpdates(locationListenerGps);
   locationManager.removeUpdates(locationListenerNetwork);
 }
public static abstract class LocationResult{
public abstract void gotLocation(Location location);
   }
 }

答案 2 :(得分:0)