Search code examples
androidgeolocationlocationmanager

How to get last known location for Location manager in Android?


I am using simple location manager object to get lastKnownLocation() of device but getting null object in return can any one tell me why ?

Code :

public Location getLocation() {
    LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);        
    if (locationManager != null) {          
        Location lastKnownLocationGPS = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        if (lastKnownLocationGPS != null) {             
            return lastKnownLocationGPS;
        } else {                
            Location loc =  locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
            System.out.println("1::"+loc);----getting null over here
            System.out.println("2::"+loc.getLatitude());
            return loc;
        }
    } else {            
        return null;
    }
}
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.location);
    getLocation();-----calling service

 }

permissions given :

 <uses-permission android:name="android.permission.INTERNET" />
 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
 <uses-permission android:name="android.permission.READ_PHONE_STATE" />
 <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
 <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

so is anything missing to set up? I have checked my location service is on in device please give some links for working examples


Solution

  • Silly thing as answer to this ...I restarted my device ...and it worked...Please ensure that your service for location are enabled and working properly