我有一个按钮,每次用户点击它,我都会调用javascriptinterface getLocation()
,如果位置服务关闭,则会让用户进行设置,让用户启用它。
我按onConnected
和onLocationChanged
获取了该位置。每次我打开我的应用程序时,onConnected
都会被触发并获取该位置。但我注意到,当我从设置中启用位置服务并立即返回应用时,onConnected
会被触发,但位置仍为null
。看起来有延迟或什么的。直到大约3秒后,我再试一次,它会起作用并为我找到位置。
以下是我的相关代码:
Android方面:
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;
}
我的问题是,我怎样才能毫不拖延地获取该位置。
答案 0 :(得分:0)
确保您在活动的 onStart()中请求位置更新,以便当您从位置设置返回时,活动将请求位置更新。
答案 1 :(得分:0)
我最终找到了出路:
为....
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);
添加一个条件:
<section>
<div id="left-box"></div>
<div id="middle-box"></div>
<div id="right-box"></div>
</section>