Hello all i know this question is too old and there are many of them but none of the solution is working for me. I am fetching latitude and longitude programmaticaly i tried below code but what is happening is for GPS every time i am getting LastKnownLocation = null also my GPS is enabled on my device, i tried this code on different devices where on some of them i am able to get latitude and longitude from GPS but for most of them it is showing null. I don't know why this code is failing for most of the cases, if any one of you know anything about this or any better way of doing it then please tell me i have spent almost a week digging what's wrong in the above code but nothing help me out.
UPDATE- Is google's FusedLocationApi free or there is limited requests per day ??
public class GPSTracker extends Service implements LocationListener {
private final Context context;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
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 (isGPSEnabled) {
Log.d("gps", "gpsenabled");
if (location == null) {
Log.d("gps", "location is null");
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null) {
Log.d("gps", "locationManager is not null");
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
Log.d("gps", "location is not null");
latitude = location.getLatitude();
longitude = location.getLongitude();
Log.d("gps", "lat: " + latitude + ", lon: " + longitude);
}
}
}
}
if (isNetworkEnabled) {
Log.d("gps", "networkenabled");
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null) {
Log.d("gps", "locationManager is not null");
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
Log.d("gps", "location is not null");
latitude = location.getLatitude();
longitude = location.getLongitude();
Log.d("gps", "lat: " + latitude + ", lon: " + longitude);
}
}
}
//
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = lm.getBestProvider(criteria, false);
Log.d("gps", "bestProvider: " + bestProvider);
Location location = lm.getLastKnownLocation(bestProvider);
Log.d("gps", "lat: " + location.getLatitude() + ", lon: " + location.getLongitude());
//
}
} catch (Exception e) {
}
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) {
latitude = 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("GPS is not enabled. Do you want to go to setttings menu ?");
alertDialog.setPositiveButton("Setting", 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 location) {
this.location = location;
latitude = getLatitude();
longitude = getLongitude();
Log.d("gps", "onLocationChanged");
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
Related
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 my app I want to show user's current location and if location is changed it will show an alert message to change the location. The problem is that it shows location chahnge message even when the phone's GPS is off. What might be the reason?
Here's my code:
protected void onResume() {
/**
* get saved Location from shared preference
*
*/
SharedPreferences sPrefs = PreferenceManager
.getDefaultSharedPreferences(Activity_Home.this);
String getL = sPrefs.getString(Utility.KEY_USER_LAT, "0.000000");
String getLo = sPrefs.getString(Utility.KEY_USER_LONG, "0.000000");
getLat = Double.parseDouble(getL);
getLog = Double.parseDouble(getLo);
gps = new GpsTracker(Activity_Home.this);
/**
* Get user current latitude and longitude and match them to stored
* latitude and longitude if distance between these latitude then Pop up
* will be show
*
* #author Ankit
*/
if (gps.canGetLocation()) {
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
System.out.println("Latitude is " + getLat);
if (getLat > 0.0) {
Location locationA = new Location("point A");
locationA.setLatitude(getLat);
locationA.setLongitude(getLog);
Location locationB = new Location("point B");
locationB.setLatitude(latitude);
locationB.setLongitude(longitude);
distance = locationA.distanceTo(locationB);
// Toast.makeText(Activity_Home.this,
// "Distance is :"+Double.toString(distance),
// Toast.LENGTH_LONG).show();
distance = distance / 1000000;
int getDistance = (int) (distance * 1000000);
System.out.println("Distance is " + getDistance);
if (getDistance > 100) {
showWarningMessage();
}
}
String lat = String.valueOf(latitude);
String lon = String.valueOf(longitude);
SharedPreferences sPref = PreferenceManager
.getDefaultSharedPreferences(Activity_Home.this);
SharedPreferences.Editor sEdit = sPref.edit();
sEdit.putString(Utility.KEY_USER_LAT, lat);
sEdit.putString(Utility.KEY_USER_LONG, lon);
sEdit.commit();
} else {
gps.showSettingsAlert();
}
super.onResume();
}
// Method for show an Alert dialog for user if user's location changed''
public void showWarningMessage() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
Activity_Home.this);
alertDialog.setCancelable(false);
// Setting Dialog Title
alertDialog.setTitle("Location Changed");
// Setting Dialog Message
alertDialog
.setMessage("It seems your location has changed, would you like to change the Branch now?");
// On pressing Settings button
alertDialog.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Activity_Home.this,
Activity_Settings.class);
startActivity(intent);
dialog.cancel();
}
});
// on pressing cancel button
alertDialog.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
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
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 100; // 100 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);
System.out.println("=====isGPSEnabled:
"+isGPSEnabled+"====isNetworkEnabled: "+isNetworkEnabled);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
System.out.println("=====notgps");
} else {
this.canGetLocation = true;
// First get location from Network Provider
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;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
* */
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(GpsTracker.this);
}
}
/**
* Function to get latitude
* */
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;
}
/**
* Function to check GPS/wifi enabled
* #return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
* */
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
alertDialog.setCancelable(false);
// Setting Dialog Title
alertDialog.setTitle("Enable GPS");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to
settings menu?");
// On pressing Settings button
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);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new
DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
// alertDialog.;
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
Here is one sample code for find location check this if it works for you
public static void LocationFind() {
try {
if (Skyhook) {
_xps.getXPSLocation(null,
// note we convert _period to seconds
(int) (_period / 1000), _desiredXpsAccuracy, _callback);
// _xps.getLocation(null, _streetAddressLookup, _callback);
} else {
Criteria criteria = new Criteria();
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
criteria.setAltitudeRequired(false);
criteria.setAccuracy(Criteria.ACCURACY_FINE);
LocationManager locationManager = (LocationManager) mcontext.getSystemService(Context.LOCATION_SERVICE);
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// Getting network status
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, locationListener);
// Log.d("Network", "Network");
if (locationManager != null) {
lastknownlocations = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (lastknownlocations != null) {
lat = lastknownlocations.getLatitude();
lng = lastknownlocations.getLongitude();
}
}
}
if (isGPSEnabled) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, locationListener);
// Log.d("Network", "Network");
if (locationManager != null) {
lastknownlocations = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (lastknownlocations != null) {
lat = lastknownlocations.getLatitude();
lng = lastknownlocations.getLongitude();
}
}
}
if (lat == 0.0 && lng == 0.0) {
lng = lastknownlocations.getLongitude();
lat = lastknownlocations.getLatitude();
}
getAddressFromLatLong(lat, lng);
}
} catch (Exception e) {
e.printStackTrace();
}
}
Try out with this service class. This sends updates to method sendLocationDataToProcess(Location location) whenever there is a different of 10 meters with respect to last location
public class AppLocationService extends Service implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener{
private LocationRequest locationRequest;
private GoogleApiClient googleApiClient;
private Context appContext;
private boolean currentlyProcessingLocation = false;
private int mInterval=0;
private final int CONNTIMEOUT=50000;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
appContext=getApplicationContext();
Toast.makeText(getBaseContext(), "Location Service Started", Toast.LENGTH_SHORT)
.show();
if (!currentlyProcessingLocation) {
currentlyProcessingLocation = true;
startTracking();
}
return START_STICKY;
}
private void startTracking() {
if (GooglePlayServicesUtil.isGooglePlayServicesAvailable(this) == ConnectionResult.SUCCESS) {
Log.v(Constants.BLL_LOG, "ConnectionResult SUCCESS");
googleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
if (!googleApiClient.isConnected() || !googleApiClient.isConnecting()) {
googleApiClient.connect();
}else{
Log.v(Constants.BLL_LOG, "NOT connected googleApiClient.connect()");
}
} else {
Log.v(Constants.BLL_LOG, "unable to connect to google play services.");
}
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
public AppLocationService() {
}
#Override
public void onConnected(Bundle bundle) {
Log.v(Constants.BLL_LOG,"onConnected");
locationRequest = LocationRequest.create();
locationRequest.setInterval(mInterval * 1000); // milliseconds
locationRequest.setFastestInterval(mInterval * 1000);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setSmallestDisplacement(MIN_DISTANCE_CHANGE_FOR_UPDATES);//dostance change
int permissionCheck = ContextCompat.checkSelfPermission(appContext, Manifest.permission.ACCESS_COARSE_LOCATION);
if (permissionCheck!= PackageManager.PERMISSION_DENIED)
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
}
#Override
public void onConnectionSuspended(int i) {
Log.v(Constants.BLL_LOG,"onConnectionSuspended");
}
#Override
public void onLocationChanged(Location location) {
Log.v(Constants.BLL_LOG, "onLocationChanged position: " + location.getLatitude() + ", " + location.getLongitude() + " accuracy: " + location.getAccuracy());
Log.v(Constants.BLL_LOG, "onLocationChanged position: location.getAccuracy()= "+location.getAccuracy());
sendLocationDataToProcess(location);
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.v(Constants.BLL_LOG,"onConnectionFailed");
}
void sendLocationDataToProcess(Location location){
//Do your logic with Location data
}
#Override
public void onDestroy() {
super.onDestroy();
if (googleApiClient != null && googleApiClient.isConnected()) {
googleApiClient.disconnect();
}
}
}
I have done a program to fetch users gps location-its working fine in some mobiles but not working in Samsung S4(i9505).
I am running a service and extended LocationListener. Below is the code:
public class MainService extends Service implements LocationListener
{
public double latitude;
public double longitude;
LocationManager mlocManager=null;
LocationListener mlocListener;
Timer timer;
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
mlocListener = this;
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
if (mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
{
final String provider = LocationManager.GPS_PROVIDER;
// start new timer thread
TimerTask task = new TimerTask()
{
#Override
public void run()
{
Location timerLoc = mlocManager.getLastKnownLocation(provider);
getFrndLocCloudAndSaveInDB();
SimpleDateFormat formata = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
String currentDateandTime = formata.format(new Date());
if(latitude>0 & longitude>0)
{locObj = new LocModel(myName, String.valueOf(latitude), String.valueOf(longitude), currentDateandTime);
Log.d("ccrc","my Loc:::"+ String.valueOf(timerLoc.getLatitude()) + " --|-- " + String.valueOf(timerLoc.getLongitude()) + "at" + currentDateandTime);}
i=i+1;
Log.d("ccrc","from timer--"+ i);
}
};
timer = new Timer(true);
timer.scheduleAtFixedRate(task, 5000, 10000);
}
else {
}
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onLocationChanged(Location loc)
{
this.latitude=loc.getLatitude();
this.longitude=loc.getLongitude();
Log.i("latusrvc", String.valueOf(latitude));
}
}
In Log-for ccrc tag i get the result in other mobiles but not showing the longitude and latitude in Samsung S4. Plus GPS is on- i have also checked that. What can be the problem really?
I'm using this class to get latitude and longitude of the current location using GPS with method canGetLocation(). If GPS isn't on we can ask to activate the GPS of the phone by showing a Dailog with method showSettingsAlert.
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location;
double latitude;
double longitude;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 2; // 10 meters
private static final long MIN_TIME_BW_UPDATES = 1000 * 5 * 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;
}
/**
* Stop using GPS listener Calling this function will stop using GPS in your
* app
* */
public void stopUsingGPS() {
if (locationManager != null) {
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
* */
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;
}
/**
* Function to check GPS/wifi enabled
*
* #return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog On pressing Settings button will
* lauch Settings Options
* */
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 location) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
In this case I use GPS,Network as a Provider, I try walking inside the building but seem like it doesn't find the location.. So, Why isProviderEnabled return true? Anyway, What is the way that i should implement ?
This is my code :
public class GPSTraker extends Service implements LocationListener {
private final Context context ;
boolean isGPSEnabled = false;
boolean isNetworkEnabled= false;
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 ;
private LocationManager locationManager;
public GPSTraker(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) {
//No providers
} 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) {
longitude = location.getLongitude();
latitude = location.getLatitude();
}
}
}*/
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
locationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES,
this
);
Log.d("GPS", "GPS");
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
longitude = location.getLongitude();
latitude = location.getLatitude();
}
}
}
}
}
}catch (Exception e){
e.printStackTrace();
Log.d("Exeception getLocation",e.toString());
}
return location;
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
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;
}
public boolean canGetLocation(){
return this.canGetLocation;
}
public void showSettingAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setTitle("GPS is setting");
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
alertDialog.setPositiveButton("Setting", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
alertDialog.show();
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
* */
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(GPSTraker.this);
}
}
}
Manifest.xml
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION">
</uses-permission>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION">
</uses-permission>
It returns true because it's enabled. You don't ask if it's able calculate your position. To get updates when your location is changed use onLocationChanged().
Im looking for a very sample example show longitude and latitude trackers with asynctask.
I find this code https://stackoverflow.com/a/6788457 but he doesn't work :/ i catch this strangely exception "provider doesn't exisit: null" in :
public boolean startService() {
try {
// this.locatorService= new
// Intent(FastMainActivity.this,LocatorService.class);
// startService(this.locatorService);
FetchCordinates fetchCordinates = new FetchCordinates();
fetchCordinates.execute();
return true;
} catch (Exception error) {
Log.i("exception", error.getMessage());
return false;
}
}
After search, I see this post (https://stackoverflow.com/a/13851305/2137454) who explain I must may be use this line :
List<String> providers = locationManager.getAllProviders();
But I don't understand where and how use this tips in my gpstracker class... Someone can help me ?
Here the complete gpstracker class :
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location = null;
double latitude = 0;
double longitude = 0;
double altitude = 0;
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.mContext = context.getApplicationContext();
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) {
Log.i("Je tombe...","...ici !");
} else {
this.canGetLocation = true;
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();
altitude = location.getAltitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
public void stopUsingGPS() {
if (locationManager != null) {
Log.i("STOPUSINGGPS", "EFFECTIF");
locationManager.removeUpdates(GPSTracker.this);
}
}
public double getLatitude() {
if (location != null) {
Log.i("LATITUDE", "EFFECTIF");
latitude = location.getLatitude();
}
return latitude;
}
public double getLongitude() {
if (location != null) {
Log.i("LONGITUDE", "EFFECTIF");
longitude = location.getLongitude();
}
return longitude;
}
public double getAltitude() {
if (location != null) {
Log.i("ALTITUDE", "EFFECTIF");
altitude = location.getAltitude();
}
return altitude;
}
public boolean canGetLocation() {
return this.canGetLocation;
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
edit : my gps is turned ON