您可以使用 LocationManager。
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
对 getLastKnownLocation() 的调用不会阻塞 - 这意味着如果当前没有可用的位置,它将返回 null - 所以您可能想看看将 LocationListener 传递给 requestLocationUpdates() 方法,这将给出你异步更新你的位置。
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
longitude = location.getLongitude();
latitude = location.getLatitude();
Toast.makeText(this, "longitude " + longitude + "latitude " + latitude, Toast.LENGTH_SHORT).show();
}
}
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 10, locationListener);
如果您想使用 GPS,您需要为您的应用授予 ACCESS_FINE_LOCATION 权限。
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
您可以在 GPS 不可用时添加 ACCESS_COARSE_LOCATION 权限,并使用 getBestProvider() 方法选择您的位置提供商。