Get current location during app launch

user915303 picture user915303 · Sep 5, 2012 · Viewed 13.9k times · Source

Good Day! I am working on an android app which monitors user location. I am using LocationManager to get users location, using the following method

public void onLocationChanged(Location theLocation) {}

Through the above method, whenever there was a user movement, I am receiving location coordinates.

But, now I am planning to get user's location immediately after their app login. Is there any way through LocationManager through which I can manually get the location coordinates after my app launch?

Answer

pyus13 picture pyus13 · Sep 5, 2012

Use this technique :

LocationManager locManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);

boolean network_enabled = locManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

Location location;

if(network_enabled){

   location = locManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

if(location!=null){
   longitude = location.getLongitude();
   latitude = location.getLatitude();
    }                
}

In this case you even no need to on GPS only your mobile network will do.

Don't forget to give the following permission in Manifest:

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