如何在Android(2.2)设备上获取用户的GPS位置

时间:2011-02-11 02:39:11

标签: java android gps android-location

我试图简单地获取用户的GPS位置,但我的应用程序在尝试获取设备的纬度和经度时崩溃。请参阅代码以了解错误发生的位置..

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE); 
    Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    final double longitude = location.getLongitude();  //error occurs here
    final double latitude = location.getLatitude();    //and here

    LocationListener locationListener = new LocationListener() {
        public void onLocationChanged(Location location) {
          // Called when a new location is found by the network location provider.
            //longitude = location.getLongitude();
            //latitude = location.getLatitude();
        }
        public void onStatusChanged(String provider, int status, Bundle extras) {}
        public void onProviderEnabled(String provider) {}
        public void onProviderDisabled(String provider) {}
      };
    //update location via GPS PROVIDER
    //can also use LocationManager.NETWORK_PROVIDER
    lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);

}

我还在清单文件中包含ACCESS_FINE_LOCATION权限:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

所以我不太清楚为什么这不起作用。任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:2)

答案 1 :(得分:0)

您的错误很可能是:lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);

这是因为getLastKnownLocation是一个非阻塞调用,并且假设应用程序刚刚启动,系统没有“最后知道的位置”。您可能希望循环,直到您没有获得getLastKnownLocation的非null值。