you can try with the LocationManager.
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
then you LocationListener which will give you asynchronous updates of your location.
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
longitude = location.getLongitude();
latitude = location.getLatitude();
}
}
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 10, locationListener);
also add permissions into your manifest file:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-feature android:name="android.hardware.location.gps" />
<uses-permission android:name="android.permission.INTERNET" />
I hope this will help you.
default it use gps and if gps not working it will use internet so you dont need wright something
Use the [LocationManager][1].
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
The call to `getLastKnownLocation()` doesn't block - which means it will return null if no position is currently available - so you probably want to have a look at passing a [LocationListener][2] to the [requestLocationUpdates() method][3] instead, which will give you asynchronous updates of your location.
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
longitude = location.getLongitude();
latitude = location.getLatitude();
}
}
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 10, locationListener);
You'll need to give your application the [ACCESS_FINE_LOCATION permission][4] if you want to use GPS.
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
You may also want to add the [ACCESS_COARSE_LOCATION permission][5] for when GPS isn't available and select your location provider with the [getBestProvider() method][6].
[1]: http://developer.android.com/intl/de/reference/android/location/LocationManager.html
[2]: http://developer.android.com/intl/de/reference/android/location/LocationListener.html
[3]: http://developer.android.com/intl/de/reference/android/location/LocationManager.html#requestLocationUpdates%28java.lang.String,%20long,%20float,%20android.app.PendingIntent%29
[4]: http://developer.android.com/intl/de/reference/android/Manifest.permission.html#ACCESS_FINE_LOCATION
[5]: http://developer.android.com/intl/de/reference/android/Manifest.permission.html#ACCESS_COARSE_LOCATION
[6]: http://developer.android.com/intl/de/reference/android/location/LocationManager.html#getBestProvider%28android.location.Criteria,%20boolean%29