2015-12-22 36 views
0

我使用這些代碼來獲得位置爲什麼安卓不能得到位置的某個時候

但有時我不能在建築物內的位置,當時的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; 
} 
+2

使用fusedLocation它非常準確,快速 – Rahul

+0

檢查這個演示http://javapapers.com/android/android-location-fused-provider/ –

+0

@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); 
} 
相關問題