LocationManager is sending Last location all time

拟墨画扇 提交于 2020-01-25 10:01:06

问题


I have involved with location problems. I am getting my first time location and if i tried for next location, it is giving me Last location all time. I changed my location may times but all time, I am getting Last latitude and longitude. I think, GPS don't refresh. If i restarted to my phone and try again. it display to correct location and if i tried again, it is displaying me Last location.

I am sharing my source code

@Override
protected void onResume() {
    super.onResume();

    if(mMap!= null)
        mMap.clear();

    LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);                
    mFragment = (SupportMapFragment) this.getSupportFragmentManager().findFragmentById(R.id.map);
    mMap = mFragment.getMap(); 
    //if(loc != null)
        //loc.reset();

    loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    if(loc != null) {
        LatLng geo = HelperUtil.getLatLng(loc);
        mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(geo, 18));
        mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
    }
    setListener();

}

private void setListener(){ 
    if(locationListener != null){
        clearListener();
    }
    Toast toast = Toast.makeText(this, this.getResources().getString(R.string.maps_loading), Toast.LENGTH_LONG);
    toast.show();                   
    locationListener = new CustomLocationListener();
    LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);                
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
    Handler handler=new Handler();
    handler.postDelayed(new TimeoutTask(locationListener), 15*1000);
}

private void clearListener(){
    if(locationListener != null){
        LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        locationManager.removeUpdates(locationListener);
        locationListener = null;
    }
}

public class CustomLocationListener implements LocationListener {
    private boolean isCompleted = false;

    public CustomLocationListener() {}

    @Override
    public void onLocationChanged(Location location) {
        isCompleted=true;
          // Called when a new location is found by the network location provider.
          if(isBetterLocation(location, loc)){
              gotLocation(location);
          }
          clearListener();
          setUserPoint();
    }

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

    @Override
    public void onProviderEnabled(String provider) {}

    @Override
    public void onProviderDisabled(String provider) {}

    public boolean isCompleted() {
        return isCompleted;
    }
}   


     public class TimeoutTask implements Runnable {

    private CustomLocationListener listener;

    public TimeoutTask(CustomLocationListener listener) {
        this.listener=listener;
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        if (listener == null || listener.isCompleted()) {
            Log.e("provider", "completed");
            System.out.println("Lat in completed= "+loc.getLatitude());
            System.out.println("Long in completed = "+loc.getLongitude());
        }
        else {
            Log.e("provider", "timeout");
            clearListener();
            setUserPoint();
        }
    }
}

protected boolean isBetterLocation(Location location, Location currentBestLocation) {
    if (currentBestLocation == null) {
        // A new location is always better than no location
        return true;
    }

    // Check whether the new location fix is newer or older
    long timeDelta = location.getTime() - currentBestLocation.getTime();
    boolean isSignificantlyNewer = timeDelta > TWO_MINUTES;
    boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES;
    boolean isNewer = timeDelta > 0;

    // If it's been more than two minutes since the current location, use the new location
    // because the user has likely moved
    if (isSignificantlyNewer) {
        return true;
    // If the new location is more than two minutes older, it must be worse
    } else if (isSignificantlyOlder) {
        return false;
    }

    // Check whether the new location fix is more or less accurate
    int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation.getAccuracy());
    boolean isLessAccurate = accuracyDelta > 0;
    boolean isMoreAccurate = accuracyDelta < 0;
    boolean isSignificantlyLessAccurate = accuracyDelta > 200;

    // Check if the old and new location are from the same provider
    boolean isFromSameProvider = isSameProvider(location.getProvider(),
            currentBestLocation.getProvider());

    // Determine location quality using a combination of timeliness and accuracy
    if (isMoreAccurate) {
        return true;
    } else if (isNewer && !isLessAccurate) {
        return true;
    } else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) {
        return true;
    }
    return false;
}

private void gotLocation(Location location){
    loc = location;
}

Please expert help me. I also noted that sometime i am not able to get location and it say timeout. Your time will be very helpful for me.


回答1:


you are using network location which doesn't provide the correct location rather than using network location you should use the GPS location for current and accurate location.

getLastKnowLocation() method doesn't provide the correct , current location for this you can refer this link.

rather than using network location use GPS location and you can find the good example of GPS location from the given link.

http://www.androidhive.info/2012/07/android-gps-location-manager-tutorial/




回答2:


For your concern .. make use of LocationClient instead of LocationManager class...

Try like this ..

LocationClient locationClient; // initialize 
Location src; // It will store your location 

then in your onCreate method ..

locationClient = new LocationClient(this, this, this);
locationClient.connect(); // this will call OnConnected method of location client

@Override
    public void onConnectionFailed(ConnectionResult arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onConnected(Bundle arg0) {
        src = locationClient.getLastLocation();
        System.out.println("======================location 1==" + src);

        // This is your location update .. it will update each time your location is  //changed 
        LocationRequest lrequest = new LocationRequest();
        lrequest.setInterval(0);
        lrequest.setSmallestDisplacement(0);

        locationClient.requestLocationUpdates(lrequest, new LocationListener() {

            @Override
            public void onLocationChanged(Location arg0) {
                Toast.makeText(getApplicationContext(),
                        "Location is 12" + arg0.getLatitude(),
                        Toast.LENGTH_SHORT).show();


            }
        });

    }

    @Override
    public void onDisconnected() {
        // TODO Auto-generated method stub

    }

OR

If you are using Google Map and need to update location of device on Google map then you may make use of Google Map methods as it will provide you current location on device rather than Last location of device ..

Try like this ..

GoogleMap myMap;

Now on Oncreate get your map reference

myMap = ((SupportMapFragment) getSupportFragmentManager()
                    .findFragmentById(R.id.map)).getMap();
myMap.setMyLocationEnabled(true);

Now when you need to get location then try like this ..

Location location = new Location();
location = myMap.getMyLocation;

That's it .. you are good to go!




回答3:


First of all make sure you are including the following two lines of code in the manifest:

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

Then I would use something similar to the below to get location updates:

public class MainActivity extends FragmentActivity implements
        GooglePlayServicesClient.ConnectionCallbacks,
        GooglePlayServicesClient.OnConnectionFailedListener,
        LocationListener {
    ...
    // Global variables
    ...
    LocationClient mLocationClient;
    boolean mUpdatesRequested;
    ...
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ...
        // Open the shared preferences
        mPrefs = getSharedPreferences("SharedPreferences",
                Context.MODE_PRIVATE);
        // Get a SharedPreferences editor
        mEditor = mPrefs.edit();
        /*
         * Create a new location client, using the enclosing class to
         * handle callbacks.
         */
        mLocationClient = new LocationClient(this, this, this);
        // Start with updates turned off
        mUpdatesRequested = false;
        ...
    }
    ...
    @Override
    protected void onPause() {
        // Save the current setting for updates
        mEditor.putBoolean("KEY_UPDATES_ON", mUpdatesRequested);
        mEditor.commit();
        super.onPause();
    }
    ...
    @Override
    protected void onStart() {
        ...
        mLocationClient.connect();
    }
    ...
    @Override
    protected void onResume() {
        /*
         * Get any previous setting for location updates
         * Gets "false" if an error occurs
         */
        if (mPrefs.contains("KEY_UPDATES_ON")) {
            mUpdatesRequested =
                    mPrefs.getBoolean("KEY_UPDATES_ON", false);

        // Otherwise, turn off location updates
        } else {
            mEditor.putBoolean("KEY_UPDATES_ON", false);
            mEditor.commit();
        }
    }
    ...
    /*
     * Called by Location Services when the request to connect the
     * client finishes successfully. At this point, you can
     * request the current location or start periodic updates
     */
    @Override
    public void onConnected(Bundle dataBundle) {
        // Display the connection status
        Toast.makeText(this, "Connected", Toast.LENGTH_SHORT).show();
        // If already requested, start periodic updates
        if (mUpdatesRequested) {
            mLocationClient.requestLocationUpdates(mLocationRequest, this);
        }
    }
}

I would recommend you take a look at this tutorial. Hope it helps you :)




回答4:


Although the best option is to switch to new Location API based on Google Play Services (http://developer.android.com/training/location/index.html), here I am trying to explain what is wrong.

You are calling the setListener() method only once in onResume(). So the listener starts listening. But on any location change you are clearing the listener. As a result you'll get a last known location at first and then you'll get maximum one location update. After that as the listener is set as null, you'll not get any update. So you can fix it simply by modifying the TimeoutTask.

public class TimeoutTask implements Runnable {

    private CustomLocationListener listener;

    public TimeoutTask(CustomLocationListener listener) {
        this.listener = listener;
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        if (listener == null || listener.isCompleted()) {
            Log.e("provider", "completed");
            System.out.println("Lat in completed= " + loc.getLatitude());
            System.out.println("Long in completed = " + loc.getLongitude());
        } else {
            Log.e("provider", "timeout");
            clearListener();
                            setUserPoint();
        }
// setting the listener again
        setListener();
    }
}


来源:https://stackoverflow.com/questions/24078924/locationmanager-is-sending-last-location-all-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!