onLocationChanged()不能被调用?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (1459)

我正在编写一个代码,它会带来当前的位置,但它不会给我这个位置,因为它从来不会调用onLocationChanged()。是否有任何方法可以找到位置。

mobileLocation在这种情况下即将到达0,所以执行进入else块。

我的代码是

public class FindLocation {
private LocationManager locManager;
private LocationListener locListener;
private Location mobileLocation;
private String provider;

public FindLocation(Context ctx){
    locManager = (LocationManager) ctx.getSystemService(Context.LOCATION_SERVICE);
    locListener = new LocationListener() {
        @Override
        public void onStatusChanged(String provider, int status,
                Bundle extras) {
        }
        @Override
        public void onProviderEnabled(String provider) {
        }
        @Override
        public void onProviderDisabled(String provider) {
        }
        @Override
        public void onLocationChanged(Location location) {
            System.out.println("mobile location is in listener="+location);
            mobileLocation = location;
        }
    };
    locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, locListener);              
    if (mobileLocation != null) {
        locManager.removeUpdates(locListener); 
        String londitude = "Londitude: " + mobileLocation.getLongitude();
        String latitude = "Latitude: " + mobileLocation.getLatitude();
        String altitiude = "Altitiude: " + mobileLocation.getAltitude();
        String accuracy = "Accuracy: " + mobileLocation.getAccuracy();
        String time = "Time: " + mobileLocation.getTime();
        Toast.makeText(ctx, "Latitude is = "+latitude +"Longitude is ="+londitude, Toast.LENGTH_LONG).show();
    } else {
        System.out.println("in find location 4");
        Toast.makeText(ctx, "Sorry location is not determined", Toast.LENGTH_LONG).show();
    }
}
   }
提问于
用户回答回答于

可能是你的代码比LocationManager更快,后者可能还没有调用onLocationChanged()。更改代码以获得最后一个已知位置,或等到你的locListener被调用时:

locManager.requestLocationUpdates(
  LocationManager.GPS_PROVIDER, 1000, 1, locListener);
mobileLocation = locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (mobileLocation != null) {
用户回答回答于

我在真正的设备上运行我的应用程序。我使用网络而不是GPS,onLocationChanged叫做:

locMan.requestSingleUpdate(LocationManager.NETWORK_PROVIDER, this, null);

扫码关注云+社区

领取腾讯云代金券