经度和纬度总是使用gps android返回零

时间:2014-03-13 06:44:24

标签: java android google-maps gps

我使用以下代码获取当前位置。但我面临的问题是,在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

}

2 个答案:

答案 0 :(得分:0)

您可以使用此课程。

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;
    }

}

答案 1 :(得分:0)

按照此Link获取设备中GPS的获取当前位置。 当用户关闭GPS时,会在设备中启用GPS显示警告对话框。