【问题标题】:The longitude and latitude always return zero using gps android经度和纬度总是使用gps android返回零
【发布时间】:2014-03-13 06:44:24
【问题描述】:

我正在使用以下代码来获取我的当前位置。但我面临的问题是,在 Gps 的情况下,纬度和经度总是返回 0.0。网络提供商工作正常。 .我已经打开手机中的GPS设置并设置了所有权限。但我仍然面临这个问题。

*/Java 代码/*

public class GpsLocationTracker extends Service implements LocationListener
{


private Context mContext;
private boolean isGpsEnabled = false;
private boolean isNetworkEnabled = false;
private boolean canGetLocation = false;
private Location mLocation;
private double mLatitude;
private double mLongitude;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATE = 10;
private static final long MIN_TIME_FOR_UPDATE = 60000;
private LocationManager mLocationManager;

/**
 * mContext constructor of the class
 */
public GpsLocationTracker(Context mContext)
{

    this.mContext = mContext;
    getLocation();
}


/**
 * method to finding the location
 */
public Location getLocation() 
{

    try {

        mLocationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);

        /*getting status of the gps*/
        isGpsEnabled = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

        /*getting status of network provider*/
        isNetworkEnabled = mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (!isGpsEnabled && !isNetworkEnabled)
        {
            /*no location provider enabled*/
            System.out.println("Gps and Network not enabled");
        } 
        else 
        {

            this.canGetLocation = true;

            /*getting location from network provider*/
            /* if (isNetworkEnabled) {

                mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_FOR_UPDATE, MIN_DISTANCE_CHANGE_FOR_UPDATE, this);

                if (mLocationManager != null) {

                    mLocation = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

                    if (mLocation != null) {

                        mLatitude = mLocation.getLatitude();

                        mLongitude = mLocation.getLongitude();
                    }
                }
             }*/
            /*if gps is enabled then get location using gps*/
            if (isGpsEnabled) 
            {
                if (mLocation == null) 
                {
                    mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_FOR_UPDATE, MIN_DISTANCE_CHANGE_FOR_UPDATE, this);

                    if (mLocationManager != null) 
                    {
                        mLocation = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                        System.out.println("location gps"+mLocation);
                        if (mLocation != null) 
                        {
                            mLatitude = mLocation.getLatitude();

                            mLongitude = mLocation.getLongitude();
                             System.out.println("Latitude gps"+mLatitude);
                                System.out.println("longitude gps"+mLongitude);
                        }

                    }
                }

                }
          // }
     }

    } catch (Exception e) {

        e.printStackTrace();
    }

    return mLocation;
}

/**
 * call this function to stop using gps in our application
 */
public void stopUsingGps() 
{

    if (mLocationManager != null) 
    {

        mLocationManager.removeUpdates(GpsLocationTracker.this);

    }
}

/**
 * @return latitude <p/> function to get latitude
 */
public double getLatitude()
{

    if (mLocation != null) 
    {

        mLatitude = mLocation.getLatitude();
    }
    return mLatitude;
}

/**
 * @return longitude function to get longitude
 */
public double getLongitude()
{

    if (mLocation != null) 
    {

        mLongitude = mLocation.getLongitude();

    }

    return mLongitude;
}

/**
 * @return to check gps or wifi is enabled or not
 */
public boolean canGetLocation() 
{

    return this.canGetLocation;
}

/**
 * function to prompt user to open settings to enable gps
 */
public void showSettingsAlert()
{

    AlertDialog.Builder mAlertDialog = new AlertDialog.Builder(new ContextThemeWrapper(mContext, R.style.AppTheme));

    mAlertDialog.setTitle("Gps Disabled");

    mAlertDialog.setMessage("gps is not enabled . do you want to enable ?");

    mAlertDialog.setPositiveButton("settings", new OnClickListener() 
    {

        public void onClick(DialogInterface dialog, int which) 
        {
            // TODO Auto-generated method stub
            Intent mIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            mContext.startActivity(mIntent);
        }
    });

    mAlertDialog.setNegativeButton("cancle", new OnClickListener()
    {

        public void onClick(DialogInterface dialog, int which)
        {
            // TODO Auto-generated method stub
            dialog.cancel();

        }
    });

    final AlertDialog mcreateDialog = mAlertDialog.create();
    mcreateDialog.show();
}

@Override
public IBinder onBind(Intent arg0) 
{
    // TODO Auto-generated method stub
    return null;
}

public void onLocationChanged(Location location) {
    // TODO Auto-generated method stub

}

public void onProviderDisabled(String provider) {
    // TODO Auto-generated method stub

}

public void onProviderEnabled(String provider) {
    // TODO Auto-generated method stub

}

public void onStatusChanged(String provider, int status, Bundle extras) {
    // TODO Auto-generated method stub

}

【问题讨论】:

  • 你是用真机测试吗?
  • 您是否在清单中授予权限?
  • 是的。我使用真实设备进行了测试,并且还在清单中授予了权限。在网络提供商中它工作正常
  • @user3228311,好的,这说明你的代码没问题,你肯定是在房间里测试,我建议你到外面去,在开阔的天空下或靠近窗户的地方。因为 GPS_PROVIDER 需要开阔的天空场。 :)
  • 好的。现在我在房间里测试。房间里有可能得到latlong吗?

标签: java android google-maps gps


【解决方案1】:

你可以使用这个类。

public class GPSTracker extends Service implements LocationListener
{   
    private final Context mContext;

    // flag for GPS Status
    boolean isGPSEnabled = false;

    // flag for network status
    boolean isNetworkEnabled = false;

    boolean canGetLocation = false;

    Location location;
    public static double latitude;
    public static double longitude;

    // The minimum distance to change updates in metters
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10
                                                                    // metters

    // The minimum time beetwen updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

    // Declaring a Location Manager
    protected LocationManager locationManager;


    public GPSTracker(Context context) { 
        this.mContext = context.getApplicationContext(); 
        getLocation();

    }

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

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

            // getting network status
            isNetworkEnabled = locationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            if (!isGPSEnabled && !isNetworkEnabled) {
                // no network provider is enabled
            } else {
                this.canGetLocation = true;

                // First get location from Network Provider
                if (isNetworkEnabled) {
                    locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);

                    Log.d("Network", "Network");

                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        updateGPSCoordinates();
                    }
                }

                // if GPS Enabled get lat/long using GPS Services
                if (isGPSEnabled) {
                    if (location == null) {
                        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);
                            updateGPSCoordinates();
                        }
                    }
                }
            }
        } catch (Exception e) {
            Log.e("Error : Location",
                    "Impossible to connect to LocationManager", e);
        }

        return location;
    }

    public void updateGPSCoordinates() {
        if (location != null) {
            latitude = location.getLatitude();
            longitude = location.getLongitude();
        }
    }

    /**
     * Stop using GPS listener Calling this function will stop using GPS in your
     * app
     */

    public void stopUsingGPS() {
        if (locationManager != null) {
            locationManager.removeUpdates(GPSTracker.this);
        }
    }

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

        return latitude;
    }

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

        return longitude;
    }


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

    /**
     * Function to show settings alert dialog
     */
    public void showSettingsAlert() {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

        // Setting Dialog Title
        // alertDialog.setTitle(R.string.GPSAlertDialogTitle);

        // Setting Dialog Message
        alertDialog.setMessage("Hello");

        // On Pressing Setting button
        alertDialog.setPositiveButton("kkkk",
                new DialogInterface.OnClickListener() {
                    @Override
                    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() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });

        alertDialog.show();
    }

    /**
     * Get list of address by latitude and longitude
     * 
     * @return null or List<Address>
     */
    public List<Address> getGeocoderAddress(Context context) {
        if (location != null) {
            Geocoder geocoder = new Geocoder(context, Locale.ENGLISH);
            try {
                List<Address> addresses = geocoder.getFromLocation(latitude,
                        longitude, 1);
                return addresses;
            } catch (IOException e) {
                // e.printStackTrace();
                Log.e("Error : Geocoder", "Impossible to connect to Geocoder",
                        e);
            }
        }

        return null;
    }

    /**
     * Try to get AddressLine
     * 
     * @return null or addressLine
     */
    public String getAddressLine(Context context) {
        List<Address> addresses = getGeocoderAddress(context);
        if (addresses != null && addresses.size() > 0) {
            Address address = addresses.get(0);
            String addressLine = address.getAddressLine(0);

            return addressLine;
        } else {
            return null;
        }
    }

    /**
     * Try to get Locality
     * 
     * @return null or locality
     */
    public String getLocality(Context context) {
        List<Address> addresses = getGeocoderAddress(context);
        if (addresses != null && addresses.size() > 0) {
            Address address = addresses.get(0);
            String locality = address.getLocality();

            return locality;
        } else {
            return null;
        }
    }

    /**
     * Try to get Postal Code
     * 
     * @return null or postalCode
     */
    public String getPostalCode(Context context) {
        List<Address> addresses = getGeocoderAddress(context);
        if (addresses != null && addresses.size() > 0) {
            Address address = addresses.get(0);
            String postalCode = address.getPostalCode();

            return postalCode;
        } else {
            return null;
        }
    }

    /**
     * Try to get CountryName
     * 
     * @return null or postalCode
     */
    public String getCountryName(Context context) {
        List<Address> addresses = getGeocoderAddress(context);
        if (addresses != null && addresses.size() > 0) {
            Address address = addresses.get(0);
            String countryName = address.getCountryName();

            return countryName;
        } else {
            return null;
        }
    }



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

    @Override
    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub

    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }

}

【讨论】:

    【解决方案2】:

    关注此Link 以从设备中的 GPS 获取当前位置。 当用户关闭 GPS 时,它会显示在设备中启用 GPS 的警报对话框。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-11
      • 1970-01-01
      • 1970-01-01
      • 2015-09-01
      • 1970-01-01
      相关资源
      最近更新 更多