2012-08-08 149 views
-2

我正在尝试访问用户设备的GPS位置,似乎无处可去。无法获取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" /> 

显然是有,我俯瞰,以获得设备位置的东西..为什么最后一个已知位置总是返回空值?

回答

1

几件事情:

  1. 在您LocationListener的你是不是做与位置事情。例如。您可以将位置保存在变量中并稍后使用。
  2. 如果供应商被禁用或设备没有任何已知位置,LocationManager.getLastKnownLocation可以返回null。
  3. 在使用模拟器时,您可以模拟位置。阅读http://developer.android.com/guide/topics/location/strategies.html#MockData
  4. 嘲笑的设备,你可以使用“假的GPS”应用,并允许在设置

希望它可以帮助模拟位置。