【问题标题】:How to get current latitude and longitude and show in a toast?如何获取当前的经纬度并在吐司中显示?
【发布时间】:2020-04-08 17:54:52
【问题描述】:

您好,我知道这个问题已经存在,但直到现在还没有得到我的解决方案。我尝试了很多方法来使用 java 在 android studio 中获取当前位置,但都显示相同的消息 location is null 并且纬度经度显示 0.0/0.0

如果有人知道解决此问题的完美解决方案吗?

【问题讨论】:

标签: android


【解决方案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();
        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() 方法选择您的位置提供商。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-05
    相关资源
    最近更新 更多