如何在android中获取移动设备的经纬度?

新手上路,请多包涵

如何使用定位工具在 android 中获取移动设备的当前纬度和经度?

原文由 deepthi 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 621
1 个回答

使用 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();
    }
}

lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 10, locationListener);

如果你想使用 GPS,你需要给你的应用程序 ACCESS_FINE_LOCATION 权限

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

您可能还想添加 ACCESS_COARSE_LOCATION GPS 不可用时的权限,并使用 getBestProvider() 方法 选择您的位置提供商。

原文由 David Webb 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题