【问题标题】:location available after few seconds after enable location services启用位置服务后几秒钟后位置可用
【发布时间】:2016-10-07 21:54:53
【问题描述】:

我有一个按钮,每次用户点击它,我都会调用javascript接口getLocation(),如果位置服务关闭,将用户带到设置让用户打开它。

我通过onConnectedonLocationChanged 获取位置。每次我打开我的应用程序时,onConnected 都会被触发并获取位置。但是我注意到,当我从设置中启用位置服务并立即返回应用程序时,onConnected 被触发,但位置仍然是null。好像有延迟什么的。直到大约 3 秒后我再试一次,它会工作并为我获取位置。

这是我的相关代码:

安卓端:

protected Location location;
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.web_view);

    webView = (WebView) findViewById(R.id.webview);

    ......
}

// JavaScript Interface for location on Pick Listing Page
public class LocationInterface
{
    @JavascriptInterface
    public String getLocation() throws JSONException
    {
        JSONObject json = new JSONObject();
        if (location != null)
        {
            json.put("lat", location.getLatitude());
            json.put("lon", location.getLongitude());
            return(json.toString());
        }
        else
        {
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivity(intent);
        }
        return(null);
    }
}

......//many override lifecycle methods here

@Override
public void onConnected(Bundle connectionHint)
{
    location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
}

@Override
public void onLocationChanged(Location newLocation)
{
    location = newLocation;
}

我的问题是,我怎样才能毫不拖延地获得位置。

【问题讨论】:

    标签: android


    【解决方案1】:

    确保您在 Activity 的 onStart() 中请求位置更新,以便当您从位置设置返回时,Activity 将请求位置更新。

    【讨论】:

    • 添加这个:LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this); ?
    • 您能分享一下您的 logcat 输出吗?
    • 当我从设置中返回时,活动会触发onConnected,它会尝试获取最后位置。还不够吗?我注意到只有几秒钟的延迟。
    【解决方案2】:

    我终于找到了出路:

    getLocation()添加一个条件:

    ....
        if (location != null)
        {
            ....
        }
        else if (location == null && isLocationEnabled(context)
        {
            long startTime = System.currentTimeMillis();
            while (location == null && (System.currentTimeMillis()-startTime) < 5000)
            {
                location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
            }
            if (location != null)
            {
                json.put("lat", location.getLatitude());
                json.put("lon", location.getLongitude());
                return(json.toString());
            }
            return(null);
        }
        else
        {
            Intent intent = ....
            ....
        }
        return(null);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-15
      • 2010-11-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多