无法获取Android中的用户位置 [英] Unable to get user location in android
问题描述
每次我运行下面的代码时,日志都会显示无位置".我不知道我要去哪里错了.
Everytime I run the code below, the log spits out "no location". I do not know where I am going wrong.
我已在清单中启用了定位服务,如下所示:
I have enabled the location services in the manifest like so :
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
我应该指出,我尝试在nexus 4(API 22)和虚拟设备(API 16,21,22)上运行此应用程序,但无济于事.
I should point out that I tried running this app on my nexus 4(API 22), and on the virtual device (API 16, 21, 22) but to no avail.
public class MainActivity extends Activity implements LocationListener {
LocationManager locationManager;
String provider;
Location location;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
provider = locationManager.getBestProvider(new Criteria(), false);
try {
location = locationManager.getLastKnownLocation(provider);
} catch (SecurityException e) {
Log.d("SE", e.getMessage());
}
if (location != null) {
Log.i("Location Info", "Location achieved!");
} else {
Log.i("Location Info", "No location :(");
}
}
我将不胜感激.
推荐答案
getLastKnownLocation()
将始终返回 null
,除非设备上的某些应用最近已请求位置更新使用特定的位置提供商.
getLastKnownLocation()
will always return null
, unless some app on the device has recently requested location updates using the particular location provider.
使用 getLastKnownLocation()
之一:
-
当您对某个位置感兴趣时,如果它碰巧很方便,但如果没有该位置,便可以生活下去,或者
when you are interested in a location if one happens to be handy, but otherwise can live without it, or
作为优化,如果 getLastKnownLocation()
返回 null
或 Location,则使用
requestLocationUpdates()
您认为太老了
as an optimization, where you use requestLocationUpdates()
if getLastKnownLocation()
either returns null
or a Location
that you deem to be too old
有关何时使用各种工具的更多指南,请参见文档. LocationManager
上的方法.
See the documentation for more guidance on when to use the various methods on LocationManager
.
这篇关于无法获取Android中的用户位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!