1

我试图简单地获取用户的 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" />

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

4

2 回答 2

2

我想你可以查看这个 StackOverflow 问题:在 Android 上获取用户当前位置的最简单、最可靠的方法是什么?

于 2011-02-11T03:59:09.517 回答
0

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

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

于 2011-02-26T13:39:07.093 回答