我正在尝试访问用户设备的 GPS 位置,但似乎无处可去。
在我的课堂上,我有以下代码,它检查是否启用了 GPS 提供程序,然后尝试获取用户最后一个已知位置。
它承认 GPS 提供商是enabled
,但是当我尝试获取最后一个已知位置时,我什么也没得到,myLocation
总是以null
.
// try to get GPS location
LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
final boolean gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (gpsEnabled) {
//request for location updates
LocationListener locationListener = new MyLocationListener();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 100, 0, locationListener);
Location myLocation;
myLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (myLocation != null) {
//we have a location!!
}
} // end if gps enabled
这是来自的代码LocationListener
public class MyLocationListener implements LocationListener
{
public void onLocationChanged(Location location) {
location.getLatitude();
location.getLongitude();
// TODO get accuracy, direction and speed.
// this method is unfinished...
}
}
这是清单文件中的权限
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
显然,我忽略了一些东西来获取设备位置。为什么最后一个已知位置总是返回 null?