Not getting countryname from latitude and longitude - android

I want to get country name from user location so for this purpose i find latitude and longitude of current location. Now i want to get country name from this lat and longi.
But problem is i am not getting country name, dont know why please check my code and help me.
HomeActivity.java:
if (checkPermissions()) {
if (isLocationEnabled()) {
mFusedLocationClient.getLastLocation().addOnCompleteListener(
new OnCompleteListener<Location>() {
#Override
public void onComplete(#NonNull Task<Location> task) {
Location location = task.getResult();
if (location == null) {
requestNewLocationData();
} else {
lat = location.getLatitude(); //here i am getting latitude and logitude value
lon = location.getLongitude();
}
}
}
);
} else {
Toast.makeText(this, "Turn on location", Toast.LENGTH_LONG).show();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
} else {
requestPermissions();
}
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address>addresses;
try{
addresses = geocoder.getFromLocation(lat, lon, 10);
if(addresses.size()>0){
for(Address adr: addresses){
if(adr.getCountryName()!= null && adr.getCountryName().length()>0){
countryname = adr.getCountryName();
latlocation.setText(countryname); //but here country name is showing nothing.
break;
}
}
}
}catch (Exception e){
e.printStackTrace();
}
Please help me.

SingleLocationProvider 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) {
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;
}
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);
try {
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);
} catch (Exception ex) {
ex.printStackTrace();
}
} 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;
}
}
}
used SingleLocationProvider for getting location and then used geocoder for getting address
SingleShotLocationProvider.requestSingleUpdate(activity,
new SingleShotLocationProvider.LocationCallback() {
#Override
public void onNewLocationAvailable(SingleShotLocationProvider.GPSCoordinates location) {
Log.d("Location", "my location is " + location.toString());
latitude = location.latitude;
longitude = location.longitude;
Geocoder coder = new Geocoder(activity);
List<Address> address;
try {
address = coder.getFromLocation(latitude,longitude, 5);
if (address != null) {
Address address1 = address.get(0);
String country= addresses.get(0).getCountryName();
}
} catch (Exception e) {
e.printStackTrace();
}
}
});

Related

No Location Provider Found in Lollipop and Marshmallow

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.

how to push longitude and latitude to server for every certain distances covered

how to push longitude and latitude to server for every certain distances covered
the requirement here to solve to push data to server accoring to 1000m every time
public class LocationUpdateIntentService extends IntentService implements LocationListener {
private static final Location TODO = null;
private Activity activity;
//Location Manager
LocationManager locationManager;
public static Boolean isRunning = false;
Location location;
Map<String, String> inputMap;
float minimumDistanceBetweenUpdates = 10;
double initialLat;
double initialLong;
double finalLat;
double finalLong;
LocationRequest locationRequest;
public LocationUpdateIntentService() {
super("locationUpdateService");
}
public LocationUpdateIntentService(Activity activity) {
super("locationUpdateService");
this.activity = activity;
}
public LocationUpdateIntentService(Activity baseActivity, Map<String, String> inputMap) {
super("locationUpdateService");
this.activity = baseActivity;
this.inputMap = inputMap;
}
#Override
public void onCreate() {
super.onCreate();
locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
/*if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
if (Permissions.getLocationPermissionStatus(activity)){
location = getLastKnownLocation();
}
} else {
location = getLastKnownLocation();
}*/
location = getLastKnownLocation();
LocationRequest request = new LocationRequest();
request.setSmallestDisplacement(minimumDistanceBetweenUpdates);
}
Handler mHandler = new Handler();
Runnable mHandlerTask = new Runnable() {
#Override
public void run() {
if (!isRunning) {
startListening();
}
mHandler.postDelayed(mHandlerTask, C.TIME_LOCATION_UPDATE);
}
};
#Override
protected void onHandleIntent(Intent intent) {
mHandlerTask.run();
}
public void startListening() {
if (location != null) {
location = getLastKnownLocation();
initialLong = location.getLongitude();
initialLat = location.getLatitude();
/* String latitudeintial = String.valueOf(location.getLatitude());
String longitudeintial = String.valueOf(location.getLongitude());
// server Call : Location Update Server Call
LocationUpdateServerCall locationUpdateServerCall = new LocationUpdateServerCall(getApplicationContext());
locationUpdateServerCall.pushLocationUpdateServerCall(latitudeintial, longitudeintial);*/
}
}
public Location getLastKnownLocation() {
Location location = null;
locationManager = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE);
List<String> providers = locationManager.getProviders(true);
for (String provider : providers) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, 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 TODO;
}
Location l = locationManager.getLastKnownLocation(provider);
if (l == null) {
continue;
}
if (location == null
|| l.getAccuracy() < location.getAccuracy()) {
location = l;
}
}
if (location == null) {
return null;
}
return location;
}
#Override
public void onLocationChanged(Location location) {
this.location = location;
if (location != null) {
/* String latitude = String.valueOf(location.getLatitude());
String longitude = String.valueOf(location.getLongitude());
// server Call : Location Update Server Call
LocationUpdateServerCall locationUpdateServerCall = new LocationUpdateServerCall(getApplicationContext());
locationUpdateServerCall.pushLocationUpdateServerCall(latitude, longitude);*/
finalLat = location.getLatitude();
finalLong = location.getLongitude();
double distance = CalculationByDistance(initialLat, initialLong, finalLat, finalLong);
if(distance == 500){
LocationUpdateServerCall locationUpdateServerCall = new LocationUpdateServerCall(getApplicationContext());
locationUpdateServerCall.pushLocationUpdateServerCall(String.valueOf(finalLat), String.valueOf(finalLat));
}
}
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
public double CalculationByDistance(double initialLat, double initialLong, double finalLat, double finalLong) {
/*PRE: All the input values are in radians!*/
double latDiff = finalLat - initialLat;
double longDiff = finalLong - initialLong;
double earthRadius = 6371; //In Km if you want the distance in km
double distance = 2 * earthRadius * Math.asin(Math.sqrt(Math.pow(Math.sin(latDiff / 2.0), 2) + Math.cos(initialLat) * Math.cos(finalLat) * Math.pow(Math.sin(longDiff / 2), 2)));
return distance;
}
}
there are distanceTo method to find distance between loction.below is example of getting distnce between to location over km; after getting specified distance put a req to send position to server;
**location.distanceTo(location) / km)**
You can use method requestLocationUpdates with LocationManager. It will reduce your work. Here is the code.
//it will call every 1000 milisec and on more than 10m distance
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 10, new android.location.LocationListener() {
#Override
public void onLocationChanged(Location location) {
//Your API calls here
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
});

How to get location either from GPS or NETWORK providers in android

In my android app I'm retrieving user location for every 3 minutes and somehow I'm doing it in the following way.problems so far I have faced are
Whenever I'm getting location updates I'm getting multiple values at same time
Sometimes I'm getting both GPS and NETWORK provider values at a time.
I need only one value and also it should be either GPS or NETWORK Provider value,How to achieve this.
Here is my Service
public class MyService extends Service {
private static final String TAG = "TESTGPS";
private LocationManager mLocationManager = null;
private static final int LOCATION_INTERVAL = 180000;
private static final float LOCATION_DISTANCE = 0.0f;
double lati,longi;
String loc_name;
private class LocationListener implements android.location.LocationListener {
Location mLastLocation;
public LocationListener(String provider) {
Log.i(TAG, "LocationListener " + provider);
mLastLocation = new Location(provider);
}
#Override
public void onLocationChanged(Location location) {
Log.i(TAG, "onLocationChanged: " + location);
Toast.makeText(getApplicationContext(), ""+location.getLatitude()+"==>"+location.getLongitude(), Toast.LENGTH_SHORT).show();
lati = location.getLatitude();
longi = location.getLongitude();
Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
try {
List<Address> addressList = geocoder.getFromLocation(
lati, longi, 1);
if (addressList != null && addressList.size() > 0) {
{
loc_name = addressList.get(0).getAddressLine(1);
}
AsyncHttpClient client = new AsyncHttpClient();
final RequestParams params = new RequestParams();
params.put("sendingJSON", composeLocation());
Toast.makeText(getApplicationContext(), "" + params, Toast.LENGTH_LONG).show();
client.post("http://192.168.0.120/gpstracker/send_location.php", params, new AsyncHttpResponseHandler() {
public void onSuccess(String response) {
Log.i("Status ==> ", "Sent to server");
}
public void onFailure(int statusCode, Throwable error, String content) {
if (statusCode == 404) {
Toast.makeText(getApplicationContext(), "Requested resource not found", Toast.LENGTH_LONG).show();
} else if (statusCode == 500) {
Toast.makeText(getApplicationContext(), "Something went wrong at server end", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Unexpected Error occcured! [Most common Error: Device might not be connected to Internet]", Toast.LENGTH_LONG).show();
}
}
});
}
} catch (IOException e) {
e.printStackTrace();
mLastLocation.set(location);
}
}
#Override
public void onProviderDisabled(String provider) {
Log.i(TAG, "onProviderDisabled: " + provider);
}
#Override
public void onProviderEnabled(String provider) {
Log.i(TAG, "onProviderEnabled: " + provider);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.i(TAG, "onStatusChanged: " + provider);
}
}
LocationListener[] mLocationListeners = new LocationListener[]{
new LocationListener(LocationManager.GPS_PROVIDER),
new LocationListener(LocationManager.NETWORK_PROVIDER)
};
#Override
public IBinder onBind(Intent intent) {
return null;
}
public int onStartCommand(Intent intent, int flags, int startId) {
//Toast.makeText(MyService.this, "Service Started", Toast.LENGTH_SHORT).show();
Log.i("Service Started", "Started");
return START_STICKY;
}
#Override
public void onCreate() {
Log.e(TAG, "onCreate");
initializeLocationManager();
try {
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[1]);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "network provider does not exist, " + ex.getMessage());
}
try {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[0]);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "gps provider does not exist " + ex.getMessage());
}
}
#Override
public void onDestroy() {
Log.e(TAG, "onDestroy");
super.onDestroy();
if (mLocationManager != null) {
for (int i = 0; i < mLocationListeners.length; i++) {
try {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, 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;
}
mLocationManager.removeUpdates(mLocationListeners[i]);
} catch (Exception ex) {
Log.i(TAG, "fail to remove location listners, ignore", ex);
}
}
}
}
private void initializeLocationManager() {
Log.i(TAG, "initializeLocationManager");
if (mLocationManager == null) {
mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
}
}
public String composeLocation()
{
ArrayList<HashMap<String, String>> locationList = new ArrayList();
HashMap<String, String> map = new HashMap();
String parsed_lati = String.valueOf(lati);
String parsed_longi = String.valueOf(longi);
map.put("e1", "123");
map.put("lati",parsed_lati);
map.put("longi",parsed_longi);
map.put("loc_name",loc_name);
locationList.add(map);
return new GsonBuilder().create().toJson(locationList);
}
}
You should first check before getting location from both. First check if location is available through gps and if not then use network to get location.
Here is a sample class which have methods for checking location.
public class GPSTracker extends Service implements LocationListener {
private final Context context;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
public boolean canGetLocation = false;
Location location;
double latitude;
double longitude;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1;
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.context = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) context.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);
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);
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;
}
public void stopUsingGPS() {
if(locationManager != null) {
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(context);
alertDialog.setTitle("GPS is settings");
alertDialog.setMessage("Turn on your GPS to find nearby helpers");
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
context.startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
#Override
public void onLocationChanged(Location arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
You should use Criteria to request location update instead of using Provider:
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
locationManager.requestSingleUpdate(criteria, listener, null);
That way you can use only one listener and the location value can be from either GPS or NETWORK provider.

how to retrieve user selection from settings in the device

my application is using GPS services now i in case the GPS is off the user have the option to navigate to the device settings and set the GPS on.
now i would like to handle the user selection,
in case the user turn on the GPS the app should run again the getLocation function other wise do nothing.
but i do not know how can i handle the result of the new activity because i run it from non activity class. the relevant method is LocationAlertDialog
this is my class code:
public class GPSportLocationManager {
private boolean gpsEnabled,networkEnabled,isLocationUpdating,tryLocating = true;
private LocationManager locationManager;
private Location currentLoc=null;
private Context context;
private OnLocationFoundListener listener;
private int networkLocCount=0,gpsLocCount=0;
public GPSportLocationManager(Context ctx,OnLocationFoundListener mListener){
this.context = ctx;
this.listener = mListener;
}
/**
* method which finding the device location.
*/
public void getLocation(){
listener.getLocationInProccess();
try {
locationManager = (LocationManager) this.context.getSystemService(Context.LOCATION_SERVICE);
gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
networkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(!gpsEnabled && !networkEnabled){
LocationAlertDialog();
}else{
if(gpsEnabled){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
Constants.GPS_MIN_TIME_BETWEEN_UPDATE,Constants.GPS_MIN_DISTANCE_CHANGE,gpsListener);
}if(networkEnabled)
{
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
Constants.NETWORK_MIN_TIME_BETWEEN_UPDATE,Constants.NETWORK_MIN_DISTANCE_CHANGE,networkListener);
}
}
ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
service.schedule(new Runnable() {
#Override
public void run() {
if(currentLoc == null){
if(gpsEnabled){
currentLoc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}else if(networkEnabled){
currentLoc = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
if(currentLoc != null && listener !=null){
locationManager.removeUpdates(gpsListener);
locationManager.removeUpdates(networkListener);
listener.onLocationFound(currentLoc);
}
}
}
},30, TimeUnit.SECONDS);
}catch (Exception e){
Toast.makeText(context,"Error while getting location"+e.getMessage(),Toast.LENGTH_LONG).show();
}
}
/**
* GPS location listener handle the callbacks.
*/
private LocationListener gpsListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
if(gpsLocCount != 0 && !isLocationUpdating){
isLocationUpdating = true;
currentLoc = location;
locationManager.removeUpdates(gpsListener);
locationManager.removeUpdates(networkListener);
isLocationUpdating = false;
if(currentLoc != null && listener !=null){
listener.onLocationFound(currentLoc);
}
}
gpsLocCount++;
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
private LocationListener networkListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
if(networkLocCount != 0 && !isLocationUpdating){
isLocationUpdating = true;
currentLoc = location;
locationManager.removeUpdates(gpsListener);
locationManager.removeUpdates(networkListener);
isLocationUpdating = false;
if(currentLoc != null && listener !=null){
listener.onLocationFound(currentLoc);
}
}
networkLocCount++;
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
public void LocationAlertDialog() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setTitle("Location settings");
alertDialog
.setMessage("We cannot retrieve your location. Please click on Settings and make sure your GPS is enabled");
alertDialog.setPositiveButton("Settings",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
context.startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
tryLocating =false;
listener.onLocationFound(currentLoc);
dialog.cancel();
}
});
alertDialog.show();
}
/**
* this function get Longitude and Latitude coordinates and send back the real street address.
* #param LATITUDE
* #param LONGITUDE
* #param ctx
* #return
*/
public String getCompleteAddressString(double LATITUDE, double LONGITUDE, Context ctx) {
String strAdd = "";
Geocoder geocoder = new Geocoder(ctx, Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(LATITUDE, LONGITUDE, 1);
if (addresses != null) {
Address returnedAddress = addresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder("");
for (int i = 0; i < returnedAddress.getMaxAddressLineIndex(); i++) {
strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
}
strAdd = strReturnedAddress.toString();
Log.w("My Current location address", "" + strReturnedAddress.toString());
} else {
Log.w("My Current location address", "No Address returned!");
}
} catch (Exception e) {
e.printStackTrace();
Log.w("My Current location address", "Can not get Address!");
}
return strAdd;
}
/**
* this function convert real address to geographical coordinates.
* #param strAddress -real address
* #return LatLng object which contain the coordinates
*/
public LatLng getLocationFromAddress(String strAddress) {
Geocoder coder = new Geocoder(context);
List<Address> address;
LatLng p1 = null;
try {
address = coder.getFromLocationName(strAddress, 5);
if (address == null) {
return null;
}
Address location = address.get(0);
location.getLatitude();
location.getLongitude();
p1 = new LatLng(location.getLatitude(), location.getLongitude() );
Log.d("coordinates",p1.latitude+""+p1.longitude);
} catch (Exception ex) {
Log.d("Location Exception", "error converting address");
ex.printStackTrace();
}
return p1;
}
public boolean isTryLocating() {
return tryLocating;
}
}

how to find location through gps on my phone

I actually wrote the below code on the onclick method of a button,but it is giving null pointer exception,plzz help
public void submit(View v)
{
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location= locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double mesg1=location.getLatitude();
double mesg2=location.getLongitude();
}
http://developer.android.com/reference/android/location/LocationManager.html
You should register a listener for location updates - see requestLocationUpdates() method.
Also add ACCESS_FINE_LOCATION permission to your Manifest.
hey follows few steps to get proper and accurate current location.
This way provided you current location both by interent as well as gps.
Step 1.
Put this class in your code.
GetCurLocation.java
public class GetCurLocation implements LocationListener,
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener {
public static LocationClient mLocationClient;
LocationRequest mLocationRequest;
public static LocationManager locationmanager;
float accuracy = 500;
Activity context;
boolean getLocRegularly = false;
int interval = 1000;
float Radius;
GoogleMap gmap;
SetOnLocationFoundListner OLF;
public interface SetOnLocationFoundListner {
public void onLocationFound(Location location, boolean getLocRegularly,
GoogleMap gmap);
}
public void RemoveUpdates() {
try {
if (mLocationClient != null)
mLocationClient.removeLocationUpdates(this);
if (locationmanager != null)
locationmanager.removeUpdates(LocUpByLocMgr);
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* radius should be in meters
*/
public GetCurLocation(Activity activity, int interval,
boolean getLocRegularly, GoogleMap gmap,
SetOnLocationFoundListner OLF, float Radius) {
this.OLF = OLF;
this.gmap = gmap;
this.context = activity;
this.getLocRegularly = getLocRegularly;
this.interval = interval;
this.Radius = Radius;
if (servicesConnected()) {
mLocationClient = new LocationClient(context, this, this);
mLocationClient.connect();
mLocationRequest = LocationRequest.create();
mLocationRequest.setInterval(interval);
mLocationRequest
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setFastestInterval(interval);
}
locationmanager = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
Criteria cr = new Criteria();
String provider = locationmanager.getBestProvider(cr, true);
locationmanager.requestLocationUpdates(provider, interval, 0,
LocUpByLocMgr);
}
private boolean servicesConnected() {
int resultCode = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(context);
if (ConnectionResult.SUCCESS == resultCode) {
return true;
} else {
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(resultCode,
(Activity) context, 0);
if (dialog != null) {
}
return false;
}
}
#Override
public void onConnectionFailed(ConnectionResult result) {
}
#Override
public void onConnected(Bundle connectionHint) {
try {
Location location = mLocationClient.getLastLocation();
Log.e("testing",
location.getLatitude() + "," + location.getLongitude()
+ "," + location.getAccuracy());
if (location.getAccuracy() < Radius) {
OLF.onLocationFound(location, getLocRegularly, gmap);
locationmanager.removeUpdates(LocUpByLocMgr);
} else
mLocationClient.requestLocationUpdates(mLocationRequest, this);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onDisconnected() {
}
#Override
public void onLocationChanged(Location location) {
try {
if (location.getAccuracy() > Radius) {
Log.e("testing LC", location.getAccuracy()
+ " Its Not Accurate");
} else {
Log.e("testing LC", location.getAccuracy() + " Its Accurate");
try {
OLF.onLocationFound(location, getLocRegularly, gmap);
if (!getLocRegularly) {
mLocationClient.removeLocationUpdates(this);
locationmanager.removeUpdates(LocUpByLocMgr);
}
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
android.location.LocationListener LocUpByLocMgr = new android.location.LocationListener() {
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onLocationChanged(Location location) {
try {
if (location.getAccuracy() > Radius) {
Log.e("testing LM", location.getAccuracy()
+ " Its Not Accurate");
} else {
Log.e("testing LM", location.getAccuracy()
+ " Its Accurate");
try {
OLF.onLocationFound(location, getLocRegularly, gmap);
if (!getLocRegularly) {
mLocationClient
.removeLocationUpdates(GetCurLocation.this);
locationmanager.removeUpdates(LocUpByLocMgr);
}
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
}
Step 2.
implement setonlocationfoundlistener in class where you want current location,
and declear one more method in your oncreate and after you will get one location found method and it return location and you can get location.getlatitude and location.getlongitude.
GetCurLocation gcl = new GetCurLocation(activity, 0, true, null, this,
2000);
Step 3. make permission
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
thats all. thanks
public void loc1(View v)
{
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
String longitude = String.valueOf(location.getLongitude());
String latitude = String.valueOf(location.getLatitude());
Toast.makeText(getApplicationContext(), "latitude",Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), "longitude",Toast.LENGTH_LONG).show();
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
}
};
// getting GPS status
boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// check if GPS enabled
if (isGPSEnabled) {
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
String longitude = String.valueOf(location.getLongitude());
String latitude = String.valueOf(location.getLatitude());
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
} else {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
String longitude = String.valueOf(location.getLongitude());
String latitude = String.valueOf(location.getLatitude());
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
} else {
String longitude = "0.00";
String latitude = "0.00";
}
}
}
}

Categories

Resources