我有一个与位置API相关的问题。
我尝试了以下代码:
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location loc = getLastKnownLocation(LocationManager.GPS_PROVIDER);
当调用getLastKnownLocation()
时,loc
始终为null
。
出了什么问题?
我有一个与位置API相关的问题。
我尝试了以下代码:
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location loc = getLastKnownLocation(LocationManager.GPS_PROVIDER);
当调用getLastKnownLocation()
时,loc
始终为null
。
出了什么问题?
除了在您的AndroidManifest.xml
文件中设置权限外,您是否已经注册了位置监听器?
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location loc = getLastKnownLocation(LocationManager.GPS_PROVIDER);
lm.requestLocationUpdates(LocationManager.GPS, 100, 1, locationListener);
locationListener
,可以完成您的任务。private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
我和你一样遇到了同样的问题,我总是收到一个空的位置对象。但最终它以一种简单的方式得到了解决。您必须拥有有效的GPS位置,因此,如果GPS未启用并且您没有足够的信号,则位置对象将始终为空。
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
这里有一些你可以使用的东西:
LocationManager lm = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = lm.getBestProvider(criteria, false);
Location loc = lm.getLastKnownLocation(bestProvider);
last_lat = loc.getLatitude();
last_lng = loc.getLongitude();
LocationManager lm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
错误:
Location loc = getLastKnownLocation(LocationManager.GPS_PROVIDER);
正确:
Location loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);