Following code works for me. I have used GPS as well Network Service to determine the current location of the device.
private void findCurrentLocation()
{
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (locationManager == null)
{
Toast.makeText(CityActivity.this, "Location Manager Not Available",
Toast.LENGTH_SHORT).show();
return;
}
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location == null)
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null)
{
lat = location.getLatitude();
lng = location.getLongitude();
myFunction(location);
}
else
{
locationListener = new LocationListener()
{
@Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2)
{;}
@Override
public void onProviderEnabled(String arg0)
{;}
@Override
public void onProviderDisabled(String arg0)
{;}
@Override
public void onLocationChanged(Location l)
{
location = l;
locationManager.removeUpdates(this);
if (l.getLatitude() == 0 || l.getLongitude() == 0)
{;}
else
{
lat = l.getLatitude();
lng = l.getLongitude();
myFunction(location);
}
}
}
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, f, locationListener);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 10f, locationListener);
locationtimer = new CountDownTimer(30000, 5000)
{
@Override
public void onTick(long millisUntilFinished)
{
if (location != null)
locationtimer.cancel();
}
@Override
public void onFinish()
{
if (location == null)
{;}
}
};
locationtimer.start();
}
}