如何在Android(2.2)设备上获取用户的GPS位置
问题描述:
我试图简单地获取用户的GPS位置,但尝试获取设备的经度和纬度时,我的应用程序崩溃。对于发生错误见代码..如何在Android(2.2)设备上获取用户的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许可AM:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
所以我不明白为什么这是行不通的。任何帮助将不胜感激!
答
你的错误是最有可能的:lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
这是因为getLastKnownLocation是一个非阻塞调用,并假设应用程序刚刚启动,系统没有“最后已知位置”。你可能想要循环,直到你没有为getLastKnownLocation获得一个非null值。
如果您遇到崩溃,这意味着您会收到一个调用堆栈。你可能想要发布它。 – EboMike 2011-02-11 02:41:51