Hello i need get location Latitude and location longitude only one no need listener location, any example?
per example in MainActivity.java
Location location = Myexample.location;
Myexample.class extends service
// code need here regards!
Hello i need get location Latitude and location longitude only one no need listener location, any example?
per example in MainActivity.java
Location location = Myexample.location;
Myexample.class extends service
// code need here regards!
LocationManager locationManager = context.getSystemService(Context.LOCATION_SERVICE);
String provider = LocationManager.GPS_PROVIDER;
Location lastKnownLocation = locationManager.getLastKnownLocation(provider);
if (null != lastKnownLocation) {
Toast.makeText(getActivity().getApplicationContext(),String.valueOf(lastKnownLocation.getLatitude() + lastKnownLocation.getLongitude() ),Toast.LENGTH_SHORT).show();
}
But check what does really getLastKnownLocation returns and does it fits in your application context. Otherwise you have to use listener pattern to obtain latest location.
But I strongly do not recommend to use getLastKnownLocation
if you want to get latest location. You could try implement something like this:
class MyFragment extends Fragment {
private void makeUseOfNewLocation(Location location) {
// some magic code which uses location object
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
LocationManager locationManager = (LocationManager)activity.getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
makeUseOfNewLocation(location);
locationManager.removeUpdates (this);
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
}
It ensures that you always get a location object and only once.