为啥Android有时无法获取位置

Posted

技术标签:

【中文标题】为啥Android有时无法获取位置【英文标题】:Why Android cannot get location sometime为什么Android有时无法获取位置 【发布时间】:2016-03-28 05:23:17 【问题描述】:

我使用这些代码来获取位置

但有时我无法获取建筑物内的位置,而此时 WIFI 已连接,位置已启用。

如何确保 getLastKnownLocation 在能够获取位置时返回位置?

LocationManager locationManager = (LocationManager)this.getSystemService(LOCATION_SERVICE);
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location == null) 

    location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

if(location==null)

    Toast.makeText(getApplicationContext(),"no location", Toast.LENGTH_SHORT).show();
    return;

【问题讨论】:

使用 fusedLocation 非常准确和快速 查看此演示 javapapers.com/android/android-location-fused-provider @Rah 好资料 【参考方案1】:

这对我有用...

    public void updateLoction(View view)
    locationManger = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    Location location = locationManger.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
    if (location != null) 
        txtLat.setText("" + location.getLatitude());
        txtLon.setText("" + location.getLongitude());
    
    locationManger.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);


private void setLocation(Location location) 
    if (location != null) 
        txtLat.setText("" + location.getLatitude());
        txtLon.setText("" + location.getLongitude());
    
    locationManger.removeUpdates(this);

【讨论】:

以上是关于为啥Android有时无法获取位置的主要内容,如果未能解决你的问题,请参考以下文章

为啥此代码无法通过 GPS 获取位置?

为啥我无法从此 jsonp 响应中获取位置?

为啥Android会在“新鲜”位置之后返回“陈旧”位置?

获取用户在Android中的位置的好方法

无法在位置更改时获取当前位置 android

权限被拒绝无法获取位置 Android