【问题标题】:Return a value from a method [duplicate]从方法返回一个值[重复]
【发布时间】:2018-08-27 20:25:50
【问题描述】:

我有这个方法来获取用户位置,我想返回myLocation变量:

mFusedLocationClient.getLastLocation().addOnSuccessListener(new OnSuccessListener<Location>() {
        @Override
        public void onSuccess(Location location) {
            // Got last known location. In some rare situations this can be null.
            if (location != null) {
                double latitude = location.getLatitude();
                double longitude = location.getLongitude();

                LatLng mylocation = new LatLng(latitude, longitude);
            }
        }
    });

我在返回 LatLng 值的函数内部有这个方法,但我无法从方法内部获取值。

【问题讨论】:

  • 在此处输入您的完整方法。我记住位置是一项服务,你必须处理你的代码取决于回调事件
  • @AbuQauod 完整的方法已经存在
  • 为此使用广播接收器或总线。
  • @SaurabhVadhva我不能使用它,因为我需要位置然后我调用函数

标签: android methods


【解决方案1】:

声明 Fused Location Client 类

private Location currentLocation; 

public Location getCurrentLocation() {
    return currentLocation;
}

mFusedLocationClient.getLastLocation().addOnSuccessListener(new OnSuccessListener<Location>() {
        @Override
        public void onSuccess(Location location) {
            // Got last known location. In some rare situations this can be null.
            if (location != null) {
                 this.currentLocation= location;
            }
        }
    });

在处理您当前位置 LatLng 的 getCurrentLocation() 之后

        if (getCurrentLocation()  != null) {
            double latitude = getCurrentLocation() .getLatitude();
            double longitude = getCurrentLocation() .getLongitude();

            LatLng mylocation = new LatLng(latitude, longitude);
        }

【讨论】:

  • 你不能再具体点吗?
猜你喜欢
  • 2012-09-20
  • 2014-08-31
  • 2014-04-04
  • 1970-01-01
  • 2018-03-19
  • 2015-06-14
  • 2019-07-29
  • 2012-02-07
  • 1970-01-01
相关资源
最近更新 更多