我无法理解整个获取用户位置的过程。我遵循了 LocationManager 的教程。它从 GPS 提供商处获取最后已知位置。据我所知,有些用户没有最后知道的位置,它返回 NULL。
我假设如果 NULL 将使用 GPS 并尝试获取用户位置,则下面的代码会这样。但事实并非如此。如何强制 android 检索用户位置?而不是只显示我的 NULL 消息而不起作用?
setContentView(R.layout.beer_location_list);
String title = "Nearby Breweries";
TextView topTitle = (TextView) findViewById(R.id.beerLocationTitle);
topTitle.setText(title);
//get user location
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location != null)
{
double longitude = location.getLongitude();
double latitude = location.getLatitude();
//construct url
String url = "myURl";
Log.d("urlTest",url);
//async task goes here
new GetNearbyBreweries(this).execute(url);
}
else{
//pop toast saying cant get location
Toast.makeText(getApplicationContext(), "Can not get your location at this time", Toast.LENGTH_LONG).show();
}
更新:
在查看了一些回复之后,为什么我不能做这样的事情来获取用户每次打开此 Activity 时的位置:
final LocationManager manager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
criteria.setAltitudeRequired(false);
criteria.setSpeedRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(false);
LocationListener listener = new LocationListener();
manager.requestSingleUpdate(criteria, listener, null);
我用
覆盖了位置监听器@Override
public void onLocationChanged(Location lastKnownLocation) {
if (lastKnownLocation != null) {
// whatever needs to be done
}
}
但我收到错误:LocationListener is abstract cannot be instantiated on the line new LocationListener();
最佳答案
通过注册一个LocationListener
并使用requestSingleUpdate
来请求更新当前位置,从而为您的位置请求一次更新。我假设您拥有应用程序 list 中列出的正确权限。请注意,您可能不会收到更新,尤其是因为较新的 Android 版本允许用户禁止应用访问位置信息。
LocationManager manager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
criteria.setAltitudeRequired(false);
criteria.setSpeedRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(false);
LocationListener listener = new LocationListener() {
@Override
public void onLocationChanged(Location lastKnownLocation) {
if (lastKnownLocation != null) {
// whatever needs to be done
}
}
manager.requestSingleUpdate(criteria, listener, null);
关于android - 无法获取所有用户位置android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20165353/