I am using GPS to get longitude and latitude of a location, but now I want to get each and every detail of location like: country, city, state, zip code, street number and so on.
Maximum details of current location.
Code:
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
String country;
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled
(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation
(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager.getLastKnownLocation
(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
private void initmainIntent() {
LocationResult locationResult = new LocationResult() {
#Override
public void gotLocation(Location location) {
if (location != null) {
Geocoder gcd = new Geocoder(getApplicationContext(),
Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(location.getLatitude(),
location.getLongitude(), 1);
if (addresses.size() > 0) {
String s = "Address Line: "
+ addresses.get(0).getAddressLine(0) + "\n"
+ addresses.get(0).getFeatureName() + "\n"
+ "Locality: "
+ addresses.get(0).getLocality() + "\n"
+ addresses.get(0).getPremises() + "\n"
+ "Admin Area: "
+ addresses.get(0).getAdminArea() + "\n"
+ "Country code: "
+ addresses.get(0).getCountryCode() + "\n"
+ "Country name: "
+ addresses.get(0).getCountryName() + "\n"
+ "Phone: " + addresses.get(0).getPhone()
+ "\n" + "Postbox: "
+ addresses.get(0).getPostalCode() + "\n"
+ "SubLocality: "
+ addresses.get(0).getSubLocality() + "\n"
+ "SubAdminArea: "
+ addresses.get(0).getSubAdminArea() + "\n"
+ "SubThoroughfare: "
+ addresses.get(0).getSubThoroughfare()
+ "\n" + "Thoroughfare: "
+ addresses.get(0).getThoroughfare() + "\n"
+ "URL: " + addresses.get(0).getUrl();
locationNotFound.setVisibility(View.GONE);
locationFound.setVisibility(View.VISIBLE);
foundLocationText.setText(s);
}
} catch (IOException e) {
e.printStackTrace();
}
background(location.getLatitude(), location.getLongitude());
}
}
};
MyLocation myLocation = new MyLocation();
myLocation.getLocation(this, locationResult);
}
public class MyLocation {
Timer timer1;
LocationManager lm;
LocationResult locationResult;
boolean gps_enabled = false;
boolean network_enabled = false;
public boolean getLocation(Context context, LocationResult result) {
// I use LocationResult callback class to pass location value from
// MyLocation to user code.
locationResult = result;
if (lm == null)
lm = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
// exceptions will be thrown if provider is not permitted.
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
}
try {
network_enabled = lm
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
}
// don't start listeners if no provider is enabled
if (!gps_enabled && !network_enabled)
return false;
if (gps_enabled)
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
locationListenerGps);
if (network_enabled)
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0,
locationListenerNetwork);
timer1 = new Timer();
timer1.schedule(new GetLastLocation(), 20000);
return true;
}
LocationListener locationListenerGps = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerNetwork);
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
LocationListener locationListenerNetwork = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
if (location != null) {
System.out.println(location.getLatitude());
}
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerGps);
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
class GetLastLocation extends TimerTask {
#Override
public void run() {
lm.removeUpdates(locationListenerGps);
lm.removeUpdates(locationListenerNetwork);
Location net_loc = null, gps_loc = null;
if (gps_enabled)
gps_loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (network_enabled)
net_loc = lm
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
// if there are both values use the latest one
if (gps_loc != null && net_loc != null) {
if (gps_loc.getTime() > net_loc.getTime())
locationResult.gotLocation(gps_loc);
else
locationResult.gotLocation(net_loc);
return;
}
if (gps_loc != null) {
locationResult.gotLocation(gps_loc);
return;
}
if (net_loc != null) {
locationResult.gotLocation(net_loc);
return;
}
locationResult.gotLocation(null);
}
}
public static abstract class LocationResult {
public abstract void gotLocation(Location location);
}
}
Here is the Tutorial to Get Current location and City name using GPS
Once you get GPS co-ordinates
By using Geocoder class you can every details
See below code snip is for getting Current City Same way you can go for other details also.
private class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location loc) {
editLocation.setText("");
pb.setVisibility(View.INVISIBLE);
Toast.makeText(
getBaseContext(),
"Location changed : Lat: " + loc.getLatitude() + " Lng: "
+ loc.getLongitude(), Toast.LENGTH_SHORT).show();
String longitude = "Longitude: " + loc.getLongitude();
Log.v(TAG, longitude);
String latitude = "Latitude: " + loc.getLatitude();
Log.v(TAG, latitude);
/*----------to get City-Name from coordinates ------------- */
String cityName = null;
Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(loc.getLatitude(),
loc.getLongitude(), 1);
if (addresses.size() > 0)
System.out.println(addresses.get(0).getLocality());
cityName = addresses.get(0).getLocality();
} catch (IOException e) {
e.printStackTrace();
}
String s = longitude + "\n" + latitude + "\n\nMy Currrent City is: "
+ cityName;
editLocation.setText(s);
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
Update (as per comment)
If you want to send this details to any contact via SMS.
I would say this page may help you
Using this code you can find the address like street, State, Country and Pin.
Geocoder geoCoder = new Geocoder(context, Locale.getDefault());
List<Address> addresses = geoCoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
String address = "";
if (addresses != null && addresses.size() >= 0) {
address = addresses.get(0).getAddressLine(0);
if (addresses != null && addresses.size() >= 1) {
address += ", " + addresses.get(0).getAddressLine(1);
}
if (addresses != null && addresses.size() >= 2) {
address += ", " + addresses.get(0).getAddressLine(2);
}
}
And you need to run this code in separate thread or in AsyncTask because it will internally call the network connection.
I somehow spent many hours to complete this task. In the below code the onMapReady device location is detected and shows a marker at that location. On click on the marker the location address is shown.
public class StoreFinder extends FragmentActivity implements
OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private GoogleMap mMap;
private GoogleApiClient googleApiClient;
private LocationRequest locationRequest;
private Location lastLocation;
private Marker currentUserLocationMarker;
private static final int Request_User_Location_Code = 99;
private double latitude;
double longitude;
private int ProximityRadius = 10000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_location);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
checkUserLocationPermission();
}
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
{
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
public boolean checkUserLocationPermission()
{
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
if (ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.ACCESS_FINE_LOCATION))
{
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, Request_User_Location_Code);
}
else
{
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, Request_User_Location_Code);
}
return false;
}
else
{
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults)
{
switch (requestCode)
{
case Request_User_Location_Code:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
{
if (googleApiClient == null)
{
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
}
else
{
Toast.makeText(this, "Permission Denied...", Toast.LENGTH_SHORT).show();
}
return;
}
}
protected synchronized void buildGoogleApiClient()
{
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
googleApiClient.connect();
}
#Override
public void onLocationChanged(Location location)
{
latitude = location.getLatitude();
longitude = location.getLongitude();
lastLocation = location;
if (currentUserLocationMarker != null)
{
currentUserLocationMarker.remove();
}
/*----------to get City-Name from coordinates ------------- */
String cityName = null;
Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(latitude, latitude, 1);
if (addresses.size() > 0)
System.out.println(addresses.get(0).getLocality());
cityName = addresses.get(0).getAddressLine(0);
} catch (IOException e) {
e.printStackTrace();
}
String s = cityName;
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title(s);
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ROSE));
currentUserLocationMarker = mMap.addMarker(markerOptions);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomBy(16));
if (googleApiClient != null)
{
LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
}
}
#Override
public void onConnected(#Nullable Bundle bundle)
{
locationRequest = new LocationRequest();
locationRequest.setInterval(1100);
locationRequest.setFastestInterval(1100);
locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
{
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, (LocationListener) this);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
}
Related
i need current location of user with the help of GPS provider.
Currently i'm getting GPS location, but in some devices i'm not getting location.
I also tried last known location and network location, but they are not accurate.
So please help by providing better solution.
My current code:
LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
MapsInitializer.initialize(getActivity());
LocationListener listener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
final double latitude = location.getLatitude();
final double longitude = location.getLongitude();
if (getActivity() == null){
return;
}
Geocoder geocoder = new Geocoder(getActivity(), Locale.getDefault());
try {
List<Address> fromLocation = geocoder.getFromLocation(latitude, longitude, 1);
Address address = null;
if (fromLocation != null && fromLocation.size() > 0) {
address = fromLocation.get(0);
final String locality = address.getLocality();
if (dataSend != null) {
dataSend.onDataSend(address);
}
fragmentMapBinding.map.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
LatLng latLng = new LatLng(latitude, longitude);
googleMap.clear();
CameraUpdate cameraUpdate = CameraUpdateFactory.newCameraPosition(new CameraPosition(latLng, 19, 0, 0));
googleMap.animateCamera(cameraUpdate);
googleMap.getUiSettings().setZoomGesturesEnabled(false);
googleMap.getUiSettings().setScrollGesturesEnabled(false);
googleMap.addMarker(new MarkerOptions().position(latLng).title("Your Location"));
}
});
}
} catch (IOException e) {
Log.e(TAG, "getMap", e);
}
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
Toast.makeText(getActivity(), s + " : " + i, Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderEnabled(String s) {
Toast.makeText(getActivity(), s, Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String s) {
Toast.makeText(getActivity(), s, Toast.LENGTH_SHORT).show();
}
};
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, listener);
I working with a project to find the address using latitude and longitude. I got answer in Jellybean but when comes to Lollipop and Marshmallow it only showing latitude and longitude, not getting address. It shows location provider is not found. Is there any error in my code?
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
mprovider = locationManager.getBestProvider(criteria, false);
if (mprovider != null && !mprovider.equals("")) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
return;
}
Location location = locationManager.getLastKnownLocation(mprovider);
locationManager.requestLocationUpdates(mprovider,5000, 0,this);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
if (location != null)
onLocationChanged(location);
else
Toast.makeText(getBaseContext(), "No Location Provider Found Check Your Code", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onLocationChanged(Location location) {
TextView longitude = (TextView) findViewById(R.id.textView);
TextView latitude = (TextView) findViewById(R.id.textView1);
longitude.setText("Current Longitude:" + location.getLongitude());
latitude.setText("Current Latitude:" + location.getLatitude());
Geocoder geo = new Geocoder(getApplicationContext(), Locale.getDefault());
// String mylocation;
try {
List < Address > addresses = geo.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
if (addresses != null && addresses.size() > 0) {
String address = addresses.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
address1.setText(address);
String city = addresses.get(0).getLocality();
textViewCity.setText(city);
String state = addresses.get(0).getAdminArea();
textViewState.setText(state);
String country = addresses.get(0).getCountryName();
textViewCountry.setText(country);
String postalCode = addresses.get(0).getPostalCode();
textViewPostal.setText(postalCode);
String knownName = addresses.get(0).getFeatureName();
System.out.println("Address >> " + address + " " +city+ " \n" + state + " \n" + country+ "\n"+postalCode+ "\n"+knownName);
}
} catch (IOException e) {
e.printStackTrace();
}
add this class.
public class SingleShotLocationProvider {
public static interface LocationCallback {
public void onNewLocationAvailable(GPSCoordinates location);
}
// calls back to calling thread, note this is for low grain: if you want higher precision, swap the
// contents of the else and if. Also be sure to check gps permission/settings are allowed.
// call usually takes <10ms
public static void requestSingleUpdate(final Context context, final LocationCallback callback) {
final LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
boolean isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (isNetworkEnabled) {
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
locationManager.requestSingleUpdate(criteria, new LocationListener() {
#Override
public void onLocationChanged(Location location) {
callback.onNewLocationAvailable(new GPSCoordinates(location.getLatitude(), location.getLongitude()));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}, null);
} else {
boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (isGPSEnabled) {
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
locationManager.requestSingleUpdate(criteria, new LocationListener() {
#Override
public void onLocationChanged(Location location) {
callback.onNewLocationAvailable(new GPSCoordinates(location.getLatitude(), location.getLongitude()));
}
#Override public void onStatusChanged(String provider, int status, Bundle extras) { }
#Override public void onProviderEnabled(String provider) { }
#Override public void onProviderDisabled(String provider) { }
}, null);
}
}
}
// consider returning Location instead of this dummy wrapper class
public static class GPSCoordinates {
public float longitude = -1;
public float latitude = -1;
public GPSCoordinates(float theLatitude, float theLongitude) {
longitude = theLongitude;
latitude = theLatitude;
}
public GPSCoordinates(double theLatitude, double theLongitude) {
longitude = (float) theLongitude;
latitude = (float) theLatitude;
}
}
}
and use like this:
SingleShotLocationProvider.requestSingleUpdate(getActivity(),
new SingleShotLocationProvider.LocationCallback() {
#Override
public void onNewLocationAvailable(SingleShotLocationProvider.GPSCoordinates location) {
lat = location.latitude;
lag = location.longitude;
}
});
here you can get lat - lag if your device location is enable. so also check that is enable or not.
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
showEnableLocationDialog();
} else {
SingleShotLocationProvider.requestSingleUpdate(getActivity(),
new SingleShotLocationProvider.LocationCallback() {
#Override
public void onNewLocationAvailable(SingleShotLocationProvider.GPSCoordinates location) {
lat = location.latitude;
lag = location.longitude;
}
});
}
public void showEnableLocationDialog() {
final android.app.AlertDialog.Builder builderDialog = new android.app.AlertDialog.Builder(getActivity());
builderDialog.setTitle("Enable Location");
builderDialog.setMessage("Please enable location for near by search");
builderDialog.setPositiveButton("Enable",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(myIntent);
}
});
builderDialog.setNegativeButton("No",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
//fetchImages();
}
});
android.app.AlertDialog alert = builderDialog.create();
alert.show();
}
and i hope you are asking run-time permission for location first. otherwise you will never get location.
I am developing an application which enable GPS and get the current location. My code is working fine in all android version expect API 23 i.e. Marshmallows. I am testing in Nexus 5 (API 23), Galaxy Note 3 (API 22).
Here is my code
public void program()
{
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MINIMUM_TIME_BETWEEN_UPDATES, MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, new MyLocationListener());
if (!locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
AlertDialog.Builder builder = new AlertDialog.Builder(NearBy.this);
builder.setTitle("Location Service is Not Active");
builder.setMessage("Please Enable your location services").setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
});
AlertDialog alert = builder.create();
alert.show();
} else if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
final String cityName = addresses.get(0).getAddressLine(0) + " ";
String stateName = addresses.get(0).getAddressLine(1) + " ";
String countryName = addresses.get(0).getAddressLine(2) + " ";
String country = addresses.get(0).getCountryName() + " ";
String Area = addresses.get(0).getSubAdminArea() + " ";
String Area1 = addresses.get(0).getAdminArea() + " ";
String Area2 = addresses.get(0).getLocality() + " ";
String Area3 = addresses.get(0).getSubLocality();
Log.e("Locaton", cityName + stateName + countryName + country + Area + Area1 + Area2 + Area3);
} catch (IOException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
}
}
}
I am getting NullpointerException at
addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
only in Nexus 5 (API 23). I also granted permission (ACCESS_FINE_LOCATION and ACCESS_COARSE_LOCATION) in both Mainfest and also during run time.
Kindly provide solution for this.
UPDATED
I have changed my code. I created a GPSTracker class and I am getting lat, Lng as 0
GPSTracker.java
public class GPSTracker extends Activity implements LocationListener {
private final Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
#TargetApi(Build.VERSION_CODES.M)
public void stopUsingGPS() {
if (locationManager != null) {
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
locationManager.removeUpdates(GPSTracker.this);
}
}
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
return latitude;
}
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
return longitude;
}
public boolean canGetLocation() {
return this.canGetLocation;
}
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
alertDialog.setTitle("GPS is settings");
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
#Override
public void onLocationChanged(Location currentLocation) {
this.location = currentLocation;
getLatitude();
getLongitude();
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
Problem
The location obtained may be null if the last know location could not be found due to various reasons. Read about it in the docs [here][2]
Reason/How i debugged it
getFromLocation does not throws a nullpointer according to documentation hence the problem is in your location object.
Read here about this method
Remedy
Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
Check if the location obtained in the above step is NOT NULL and then proceed with the geocoder.
Code snippet
...
else if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(location == null) {
log.d("TAG", "The location could not be found");
return;
}
//else, proceed with geocoding.
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
Fetching the location - An example
Read here
Complete code
View it here
First In marshmallow add all permission on run time also. Otherwise Please restart your mobile and then check again.
In the Android Developer guide, Google showed how to use the Google Play Services API in an activity class. What is the best way to offload the API calls into a separate class?
public class GPSresource implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private Location location; // location
private double latitude; // latitude
private double longitude; // longitude
private GoogleApiClient mGAC;
private Context mContext;
public static final String TAG = "GPSresource";
public GPSresource(Context c)
{
mContext = c;
try {
buildGoogleApiClient();
mGAC.connect();
}
catch(Exception e)
{
Log.d(TAG,e.toString());
}
}
protected synchronized void buildGoogleApiClient() {
mGAC = new GoogleApiClient.Builder(mContext)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
#Override
public void onConnected(Bundle bundle) {
location = LocationServices.FusedLocationApi.getLastLocation(mGAC);
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
}
The code I wrote above does not work since onConnected is never called since this is not an activity. Is there a better way to separate the GPS services from the Main Activity or is that the only option(If so, is there a reason as to why?) Perhaps making a thread in the main activity to run in the background?
Thanks!
onConnected is called, I made a mistake with reading the logs!
Here is an example :
public class LocationManager implements LocationListener {
private LocationManager locationManager;
public LocationManager()
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (locationManager.getAllProviders().contains(LocationManager.GPS_PROVIDER))
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
if (locationManager.getAllProviders().contains(LocationManager.NETWORK_PROVIDER))
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
Location mobileLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (mobileLocation != null)
{
onLocationChanged(mobileLocation);
}
Location netLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (netLocation != null)
{
onLocationChanged(netLocation);
}
}
#Override
public void onLocationChanged(Location loc) {
String longitude = "Longitude: " + loc.getLongitude();
//Log.v(TAG, longitude);
String latitude = "Latitude: " + loc.getLatitude();
// Log.v(TAG, latitude);
/*------- To get city name from coordinates -------- */
String cityName = null;
Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(loc.getLatitude(),
loc.getLongitude(), 1);
// Log.e(TAG, "addr : " + addresses.toString());
if (addresses.size() > 0)
cityName = addresses.get(0).getLocality();
}
catch (IOException e) {
e.printStackTrace();
}
String s = longitude + "\n" + latitude + "\n\nMy Current City is: " + cityName;
Log.e(TAG, "location : " + s);
}
#Override
public void onProviderDisabled(String provider) {
Log.d("Latitude", "disable");
}
#Override
public void onProviderEnabled(String provider) {
Log.d("Latitude","enable");
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d("Latitude","status");
}
public void pause() {
if (locationManager != null)
{
locationManager.removeUpdates(this);
locationManager = null;
}
}
public void destroy() {
if (locationManager != null)
{
locationManager.removeUpdates(this);
locationManager = null;
}
}
}
I want to get current longitude and latitude as int
So I use this code
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
0, this);
Location location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
try {
gps_enabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
}
try {
network_enabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
}
// don't start listeners if no provider is enabled
if (!gps_enabled && !network_enabled) {
....Notify
}
if (gps_enabled) {
if (location != null) {
longitude =(int) (location.getLongitude()*1e6);
latitude = (int) (location.getLatitude()*1e6);
String accuracy = "Accuracy: " + location.getAccuracy();
}
}
if (network_enabled) {
if (location != null) {
longitude =(int) (location.getLongitude()*1e6);
latitude = (int) (location.getLatitude()*1e6);
String accuracy = "Accuracy: " + location.getAccuracy();
}
}
locationManager.removeUpdates(this);
Unfortunately longitude and latitude are always null.
I have all permission needed in the manifest.
How can I fix this issue?
Well this is what i use for location listener
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
public class LocationUtils implements LocationListener{
Context context;
private String provider;
private LocationManager locationManager;
private String latitude="no value";
private String longitude="no value";
public LocationUtils(Context context) {
this.context=context;
// Get the location manager
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the locatioin provider -> use
// default
latitude="no value";
longitude="no value";
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
/*Toast.makeText(context, "Provider " + provider + " has been selected.",
Toast.LENGTH_SHORT).show();*/
// System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {
/*Toast.makeText(context, "Location not available",
Toast.LENGTH_SHORT).show();*/
}
}
#Override
public void onLocationChanged(Location location) {
double lat = (double) (location.getLatitude());
double lng = (double) (location.getLongitude());
latitude = lat + "";
longitude = lng + "";
/* Toast.makeText(context, " lat: "+lat +" Long:"+lng,
Toast.LENGTH_SHORT).show(); */
}
#Override
public void onProviderDisabled(String provider) {
//Toast.makeText(context, "Disabled provider " + provider,
// Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderEnabled(String provider) {
//Toast.makeText(context, "Enabled new provider " + provider,
// Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
public String getLatitude() {
return latitude;
}
public String getLongitude() {
return longitude;
}
}
Now in your activity u can get
LocationUtils appLocationManager = new LocationUtils(getContext());
String latitude = appLocationManager.getLatitude();
String longitude = appLocationManager.getLongitude();
Also add
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
in your manifest file
First check the GPS enabled in your device.
Check all the permissions included in the manifest
You are fetching the last known location using the GPS provider so remove that line and fetch the location individually for both the provider(There should be possible that your GPS is not available at that time so you did not get the location and you are fetching the last known location using the GPS so it can be null and if location will be null then it will not goes inside the conditions like if(network_enabled) and if(gps_enabled).).
In short check the Last known location of GPS if it is null then try to get the location using the Location provider and use that location.
public class SMS_Service extends Service {
private final String LOGTAG = "SMS_Service";
String latLongString;
String addressString;
double altitude;
int LAC;
int mcc = 0;
int mnc = 0;
String pn_no;
Altitude_Details ld = new Altitude_Details();
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
Log.e(LOGTAG, "created");
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Log.e(LOGTAG, "destroyed");
}
#Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
Log.e(LOGTAG, "started");
SmsManager sms = SmsManager.getDefault();
// get phone number from shared preference
SharedPreferences default1 = getSharedPreferences("Device",
MODE_WORLD_WRITEABLE);
pn_no = default1.getString("Phone_NO", "");
Log.e("phone_no in sms service", pn_no);
String From = intent.getStringExtra("From");
String Msg = intent.getStringExtra("Msg"); // get message from intent
Log.e("ON start:", "" + From);
Log.e("ON start:", "" + Msg);
String number = From.substring(7, 11);
Log.e("ON start: SUBSTRING", "" + number);
// check msg for Location keyword match or not
if (Msg.equals("LOCATION") && pn_no.equals(number)) {
Log.e("location:", "Location found");
TelephonyManager tel = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
String networkOperator = tel.getNetworkOperator();
// find MNC and MCC
if (networkOperator != null) {
mcc = Integer.parseInt(networkOperator.substring(0, 3));
mnc = Integer.parseInt(networkOperator.substring(3));
Log.e("MCC", "" + mcc);
Log.e("MNC", "" + mnc);
}
// find LAC for GSM
if (tel.getPhoneType() == TelephonyManager.PHONE_TYPE_GSM) {
final GsmCellLocation location = (GsmCellLocation) tel
.getCellLocation();
if (location != null) {
LAC = location.getLac();
Log.e("cell location", "LAC: " + location.getLac()
+ " CID: " + location.getCid());
}
}
LocationManager locationManager;
String context = Context.LOCATION_SERVICE;
locationManager = (LocationManager) getSystemService(context);
String provider = LocationManager.GPS_PROVIDER;
Location location = locationManager.getLastKnownLocation(provider);
// update method return latest location
updateWithNewLocation(location);
// location change then listner called
locationManager.requestLocationUpdates(provider, 2000, 10,
locationListener);
// send mcc,mnc,latitude,longitude,altitude,address,Link in message
String Url = "http://itouchmap.com/latlong.html";
sms.sendTextMessage(pn_no, null, "\nLocation:\n" + "MCC: " + mcc
+ "\nMNC: " + mnc + "\nLAC:" + LAC + latLongString
+ "\nAltitude:" + altitude + "feet"
+ "\nGo to Below site:\n" + Url, null, null);
sms.sendTextMessage(pn_no, null, "\nAddress:\n" + addressString,
null, null);
// stop service automatically
SMS_Service.this.stopSelf();
}
else {
Log.e("loation:", "Location not found");
SMS_Service.this.stopSelf();
}
}
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
updateWithNewLocation(location);
}
public void onProviderDisabled(String provider) {
updateWithNewLocation(null);
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
private void updateWithNewLocation(Location location) {
// TODO Auto-generated method stub
addressString = "\nno address found";
// check location get or not from provider
if (location != null) {
// get latitude and longitude
double latitude = location.getLatitude();
double longitude = location.getLongitude();
latLongString = "\nLat:" + latitude + "\nLong:" + longitude;
Log.e("location", "" + latLongString);
// get altitude from method
altitude = ld.getElevationFromGoogleMaps(latitude, longitude);
Log.e("Altitude", "" + altitude);
// find address from latitude and longitude
Geocoder gc = new Geocoder(this, Locale.getDefault());
try {
List<Address> addresses = gc.getFromLocation(latitude,
longitude, 1);
StringBuilder sb = new StringBuilder();
if (addresses.size() > 0) {
Address address = addresses.get(0);
for (int i = 0; i <= address.getMaxAddressLineIndex(); i++)
sb.append(address.getAddressLine(i)).append("\n");
}
addressString = sb.toString();
Log.e("Address", "" + addressString);
} catch (IOException e) {
}
} else {
latLongString = "\n No location found";
Log.e("location", "" + latLongString);
}
}
}
hey you can make the service and use this code to get altitude and latitude and decode this using class
Try This code
double longitude,latitude;
int lon,lat;
getcurrentloc.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
Toast.makeText(GpsLocationFinder.this, "Enable Your GPS", Toast.LENGTH_LONG).show();
}else{
LocationResult locationResult=new LocationResult() {
#Override
public void gotLocation(Location location) {
// TODO Auto-generated method stub
longitude=location.getLongitude();
latitude=location.getLatitude();
lon=(int)longitude;
lat=(int)latitude;
Toast.makeText(GpsLocationFinder.this, "Current Longitude"+longitude+" Current Latitude"+latitude,Toast.LENGTH_LONG).show();
}
};
MyLocation myLocation = new MyLocation();
myLocation.getLocation(GpsLocationFinder.this, locationResult);
}
}
});
And the MyLocation Class is Below
public class MyLocation {
Timer timer1;
LocationManager lm;
LocationResult locationResult;
boolean gps_enabled=false;
boolean network_enabled=false;
double longitude,latitude;
public boolean getLocation(Context context, LocationResult result)
{
//I use LocationResult callback class to pass location value from MyLocation to user code.
//Log.e("GPS DISTANCE","GPS Enabled");
locationResult=result;
if(lm==null)
lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
//exceptions will be thrown if provider is not permitted.
//don't start listeners if no provider is enabled
//try{
try{
gps_enabled=lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
}catch(Exception ex){
}
try{
network_enabled=lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}catch(Exception ex){
}
if(!gps_enabled && !network_enabled){
return false;
}
if(gps_enabled){
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 100, 100, locationListenerGps);
}
if(network_enabled)
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListenerNetwork);
timer1=new Timer();
timer1.schedule(new GetLastLocation(), 30000);
return true;
}
LocationListener locationListenerGps = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerNetwork);
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
LocationListener locationListenerNetwork = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerGps);
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
class GetLastLocation extends TimerTask {
#Override
public void run() {
lm.removeUpdates(locationListenerGps);
lm.removeUpdates(locationListenerNetwork);
Location net_loc=null, gps_loc=null;
if(gps_enabled)
gps_loc=lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(network_enabled)
net_loc=lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
//if there are both values use the latest one
if(gps_loc!=null && net_loc!=null){
if(gps_loc.getTime()>net_loc.getTime())
locationResult.gotLocation(gps_loc);
else
locationResult.gotLocation(net_loc);
return;
}
if(gps_loc!=null){
locationResult.gotLocation(gps_loc);
return;
}
if(net_loc!=null){
locationResult.gotLocation(net_loc);
return;
}
locationResult.gotLocation(null);
}
}
public static abstract class LocationResult{
public abstract void gotLocation(Location location);
}
}