【问题标题】:LocationManager is sending Last location all timeLocationManager 一直在发送最后一个位置
【发布时间】:2014-06-06 09:50:16
【问题描述】:

我遇到了位置问题。我得到了我的第一个位置,如果我尝试下一个位置,它总是给我最后一个位置。我可能多次更改我的位置,但一直以来,我都得到了最后的纬度和经度。我认为,GPS不刷新。 如果我重新启动手机并重试。它显示到正确的位置,如果我再试一次,它会显示我最后的位置。

我正在分享我的源代码

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

请高手帮帮我。我还注意到有时我无法获得位置并且它说超时。你的时间对我很有帮助。

【问题讨论】:

  • 您使用什么设备进行测试??什么版本的操作系统。
  • 关于使用相同 locationManager 从两个源连续请求更新有什么特别之处吗?-> locationManager.requestLoc...Updates(LocationManager.GPS_PROVIDER, 0...Listener); locationManager.requestLoc...Updates(LocationManager.NETWORK_PROVIDER,...Listener);?检查this link, same logic applies。尝试从每个提供者那里获取位置..一个接一个,根据您是否获得位置,记录哪个来源是所获取的位置。仅供参考,您的请求没有排队

标签: android gps locationmanager geo


【解决方案1】:

您使用的网络位置不能提供正确的位置,而不是使用网络位置,您应该使用 GPS 位置来获取当前和准确的位置。

getLastKnowLocation() 方法没有提供正确的当前位置,您可以参考这个link。

而不是使用网络位置使用 GPS 位置,您可以从给定的链接中找到 GPS 位置的好例子。

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

【讨论】:

  • 我已修复但未发表评论。你给了我我用过和修复过的东西:)
【解决方案2】:

为了您的关注..使用 LocationClient 而不是 LocationManager 类...

像这样试试..

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

然后在你的 onCreate 方法中..

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

    }

或

如果您使用 Google Map 并且需要在 Google Map 上更新设备的位置,那么您可以使用 Google Map 方法,因为它会为您提供设备上的当前位置,而不是设备的最后位置..

像这样试试..

谷歌地图我的地图;

现在在 Oncreate 上获取您的地图参考

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

现在,当您需要获取位置时,请尝试这样 ..

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

就是这样..你可以走了!

【讨论】:

    【解决方案3】:

    首先确保清单中包含以下两行代码:

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

    然后我会使用类似于下面的内容来获取位置更新:

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

    我建议你看看this tutorial. 希望对你有帮助:)

    【讨论】:

      【解决方案4】:

      虽然最好的选择是切换到基于 Google Play 服务 (http://developer.android.com/training/location/index.html) 的新 Location API,但我在这里试图解释什么是错误的。

      您在 onResume() 中只调用了一次 setListener() 方法。于是听者开始听。但是在任何位置更改时,您都会清除侦听器。因此,您将首先获得最后一个已知位置,然后您将获得最多一个位置更新。之后,由于侦听器设置为 null,您将不会获得任何更新。所以你可以简单地通过修改 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();
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2017-08-29
        • 1970-01-01
        • 1970-01-01
        • 2018-06-26
        • 2017-01-05
        • 2012-10-07
        • 1970-01-01
        • 2014-04-03
        • 1970-01-01
        相关资源
        最近更新 更多