CL So
CL So

Reputation: 3759

Why Android cannot get location sometime

I use these code to get location

But sometime I cannot get the location inside building, and that time the WIFI is connected, Location is enabled.

How can I make sure getLastKnownLocation will return location when it is able to get location?

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;
}

Upvotes: 0

Views: 407

Answers (1)

SUTHANSEE
SUTHANSEE

Reputation: 332

This works for me...

    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);
}

Upvotes: 1

Related Questions