can't find the exact current location in andro

2020-02-12 03:20发布

问题:

I have use this below code for find the current location but i got that some devices(samsung 7' and 10'inch and nexus 10'inch) exact current locations,but unfoirtunately i can't find the locations in samsung s3.

I don't have any idea ,what is issue.no find the locations.

here is my code:

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;
double latitude;
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;
    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)
    {
        //e.printStackTrace();
        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(R.string.GPSAlertDialogMessage);

    //On Pressing Setting button
    alertDialog.setPositiveButton(R.string.settings, 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(R.string.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) 
{   
}

@Override
public void onProviderDisabled(String provider) 
{   
}

@Override
public void onProviderEnabled(String provider) 
{   
}

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

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

}

回答1:

When the location comes in check for accuracy. If its not accurate enough then don't process it.

@Override
public void onLocationChanged(Location location) {
        if (!location.hasAccuracy()) {
            return;
        }
        if (location.getAccuracy() > 5) {
            return;
        }
     // do something with location accurate to 5 meters here.
    }


回答2:

Do this, Load the application in your device, move to open sky, run the application, wait for 2 minutes. Come back to office inside, and then execute above code

It worked for me.

Hope it helps you.



回答3:

We worked in Samsung devices and had issues too. Just ensure the following:

  1. GPS is on (Street Level should also be enabled)
  2. Mobile Network is enabled (If required, also enable Use packet data option)
  3. Download and install some 3rd party widgets in your phone and wait till the location coordinates appear/refresh in the widget. (This is because the widgets have timeout concept integrated in them and keep trying repeatedly to get coordinates)
  4. Goto Google-maps from the device and check if your location is being identified. (Sometimes, we have observed that Google Maps would be able to identify coordinates where as we would not be able to!!)
  5. Ensure that the GPS Satellite signal on the notification header bar is blinking.
  6. If required, set a timer for refresh and add toast messages to display lat long once obtained.

For samsung device alone, for the first time, the GPS Coordinates do not get reflected immediately (It is null and can last upto half an hour :( How Annoying!! ). So, we used to wait outside the office for some time till the GPS coordinate is recieved.



回答4:

I had the same problem. The point is: You need a time-gap between your "requestLocationUpdates" and "getLastKnownLocation"

Try to start requestLocationUpdates in the "onStart" or "onCreate" method.

protected void onStart() {

   super.onStart();
   locationManager.requestLocationUpdates(
                      LocationManager.GPS_PROVIDER,
                      MIN_TIME_BW_UPDATES,
                      MIN_DISTANCE_CHANGE_FOR_UPDATES, this);

}

This activates your GPS. You have to wait some seconds until it found some locations. So i put the "getlastKnownLocation" - method in an OnClickEvent. If no location is found it just displays a Toast.

public void onClick(View v) {

  m_CurrentLocation = m_LocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
  if (m_CurrentLocation != null)
       // Your action with the last known location
  else
       Toast.makeText(YourActivity.this, "No GPS Location found", Toast.LENGTH_SHORT).show();
}


回答5:

There are numerous bugs with LocationManager, why don't you try using fused location provider with LocationClient instead. The devs at Google have recommended this as well during the last Google I/O.

Unless the device runs on versions older than Froyo which do not have play services, there is no reason to use LocationManager.