getLastKnownLocation sometimes returns null - android

Let me start by acknowledging that there are many results when you search for this particular question. Yet, nothing I've tried, according to those answers, works. Sometimes I get the location, sometimes I don't. If I play with the Location enabling/disabling I always get null when calling getLastKnownLocation. If I sometimes manually revoke the Location permission and enable it again, it works. I've tried changing the LocationManager to location = locationManager .getLastKnownLocation(LocationManager.PASSIVE_PROVIDER); but it doesn't work.
Basically, I am doing the following:
public class GPSTracker implements LocationListener {
public static final int LOCATION_SETTINGS_REQUEST_CODE = 109;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;
private static final long MIN_TIME_BW_UPDATES = 1000 * 60;
private static boolean isGpsStatusChanged = false;
private static AlertDialog.Builder alertDialog;
private LocationManager locationManager;
private boolean canGetLocation = false;
private Location location;
private double latitude;
private double longitude;
private NewLocationListener newLocationListener;
public interface NewLocationListener {
void onLocationChanges(Location location);
}
public GPSTracker() {
}
#SuppressWarnings("all")
public Location getLocation() {
try {
locationManager = (LocationManager) BaseApplication.getContext().getSystemService(Context.LOCATION_SERVICE);
// getting GPS status
boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
boolean isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} 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("GPSTracker", "Network");
if (locationManager != null) {
Log.d("GPSTracker", "Network - location manager != null");
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
Log.d("GPSTracker", "Network - last known location != null");
latitude = location.getLatitude();
longitude = location.getLongitude();
newLocationListener.onLocationChanges(location);
}
}
}
// 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("GPSTracker", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Log.d("LastKnownLocation", "Location: " + locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER));
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
newLocationListener.onLocationChanges(location);
}
}
}
}
}
} catch (Exception e) {
Log.e(Constants.TAG, e.getMessage(), e);
}
return location;
}
public static boolean isGpsEnabled() {
LocationManager locationManager = (LocationManager) BaseApplication.getContext().getSystemService(Context
.LOCATION_SERVICE);
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
#SuppressWarnings("all")
public void stopUsingGPS() {
if (locationManager != null) {
locationManager.removeUpdates(GPSTracker.this);
}
}
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
public boolean canGetLocation() {
return this.canGetLocation;
}
public void setNewLocationListener(NewLocationListener newLocationListener) {
this.newLocationListener = newLocationListener;
}
public void removeLocationListener() {
this.newLocationListener = null;
}
#SuppressWarnings("InlinedApi")
public void showSettingsAlert(final Context context) {
if (alertDialog != null) {
return;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
alertDialog = new AlertDialog.Builder(context, android.R.style.Theme_Material_Light_Dialog_Alert);
} else {
alertDialog = new AlertDialog.Builder(context);
}
alertDialog.setTitle(R.string.gps_window_title);
alertDialog.setMessage(R.string.gps_window_message);
alertDialog.setPositiveButton(R.string.gps_window_button_positive, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
((Activity) context).startActivityForResult(intent, LOCATION_SETTINGS_REQUEST_CODE);
}
});
alertDialog.setNegativeButton(R.string.gps_window_button_negative, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show().setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
alertDialog = null;
}
});
}
#Override
public void onLocationChanged(Location location) {
if (newLocationListener != null) {
newLocationListener.onLocationChanges(location);
}
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public static boolean isGpsStatusChanged() {
return isGpsStatusChanged;
}
public static void setIsGpsStatusChanged(boolean isGpsStatusChanged) {
GPSTracker.isGpsStatusChanged = isGpsStatusChanged;
}
}
And then in my fragment:
private void statGPSLocationTracking() {
Log.d(Constants.TAG, "start gps update");
// check if GPS enabled
gpsTracker = new GPSTracker();
gpsTracker.setNewLocationListener(newLocationListener);
gpsTracker.getLocation();
if (!gpsTracker.canGetLocation()) {
Log.d(Constants.TAG, "GPS not enabled, show enable dialog");
// stop the gps tracker(removes the location update listeners)
gpsTracker.stopUsingGPS();
// ask user to enable location
gpsTracker.showSettingsAlert(getActivity());
}
}
private GPSTracker.NewLocationListener newLocationListener = new GPSTracker.NewLocationListener() {
#Override
public void onLocationChanges(Location loc) {
if (getActivity() == null) {
return;
}
// GPS location determined, load the web page and pass the coordinates in the header location section
Log.d(Constants.TAG, "Location listener onLocationChanges: " + loc);
infoManager.setCurrentLocation(loc);
checkRadioInfoNeeded();
// stop the gps tracker(removes the location update listeners)
gpsTracker.stopUsingGPS();
}
};

Without this location permission android.Manifest.permission.ACCESS_FINE_LOCATION the getLastKnownLocation() will always return null.
getLastKnownLocation() does not return location immediately, it takes some time.
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;
private static final long MIN_TIME_BW_UPDATES = 1000 * 60;
this to
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 0;
private static final long MIN_TIME_BW_UPDATES = 5 * 1000;
Also remove your code which gets location from network. Go to Google maps and see if maps is able to detect your current location. If your map is able to get location then your code too should get location place breakpoints and see where the real issue is.

Related

How to fetch location coordinates in flight mode or sim card absent state?

I am working on an android application in that application i need to fetch location coordinates even when device is in flight mode or even sim card absent state. I had tried with the below code but i am getting latitude and longitude as 0.0 generally if network is there its working fine. Please help me to solve this.
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 = 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; //getting context
getLocation(); //method calling
}
public Location getLocation() {
try {
//checkPermissions();
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;
// First get location from Network Provider
if (isNetworkEnabled) {
try {
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);
}
} catch (SecurityException e) {
// Toast.makeText(mContext, e.toString(), Toast.LENGTH_LONG).show();
}
if (location != null) {
latitude = location.getLatitude(); //getting latitude
longitude = location.getLongitude(); //getting longitude
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
try {
if (location == null) { //checking location whether null or not
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) { //if not equals null
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude(); //getting latitude from GPS
longitude = location.getLongitude(); //getting longitude from GPS
}
}
}
} catch (SecurityException e) {
// Toast.makeText(mContext, e.toString(), Toast.LENGTH_LONG).show();
}
}
//Toast.makeText(mContext, "Airplane mode is On.Please disable ", Toast.LENGTH_LONG).show();
//airplanemodealert();
} 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) {
try {
locationManager.removeUpdates(GpsTracker.this);
} catch (SecurityException e) {
// Toast.makeText(mContext, e.toString(), Toast.LENGTH_LONG).show();
}
}
}
/**
* Function to get latitude
*/
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude(); //getting latitude
}
// return latitude
return latitude;
}
/**
* Function to get longitude
*/
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude(); //getting longitude
}
// return longitude
return longitude;
}
private static boolean isAirplaneModeOn(Context context) {
return Settings.System.getInt(context.getContentResolver(),
Settings.System.AIRPLANE_MODE_ON, 0) != 0;
}
private void showAlert() {
android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(mContext);
builder.setMessage("Airplane mode is On.Please disable ");
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
builder.show();
}
/**
* 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);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// 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();
}
public void airplanemodealert() {
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setMessage("Airplane mode is On.Please disable ");
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
builder.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;
}

Android GPS tracks wrong location

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();
}
}
}

Why isn't gps location working on samsung mobile?

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;
}
}

GPS and Wifi are not enabled but isProviderEnabled is returning always true

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().

LatLng return 0,0

I am trying to create an app that shows my current location
I have all the permisson neccessary,
I have another class name GPS tracker to get my gps locations
Heres my code :
GPSTracker gpsTracker = new GPSTracker(this);
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
latitude = gpsTracker.latitude;
longitude = gpsTracker.longitude;
LatLng latLng = new LatLng(latitude, longitude);
map.moveCamera(CameraUpdateFactory.newLatLng(latLng));
map.animateCamera(CameraUpdateFactory.zoomTo(18));
Here is the GPSTracker class:
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 = 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;
// 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);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// 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();
}
#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;
}
}
DO NOT USE THE GPS TRACKER CLASS. It's horribly horribly broken. In so many ways I wrote a long blog post about it tonight: see http://gabesechansoftware.com/location-tracking/
Here's the ways its broken:
1)It doesn't track GPS. Sometimes it tracks network location instead
2)The canGetLocation function is broken. It returns true before it has a location
3)Its horribly inefficient, forcing you to poll.
4)It doesn't differentiate stale from fresh data- and doesn't let you do it either
I'd go on but I already wrote it up tonight.
I wrote a much better GPS tracker library at my blog. Here it is repeated for SO use
LocationTracker.java
package com.gabesechan.android.reusable.location;
import android.location.Location;
public interface LocationTracker {
public interface LocationUpdateListener{
public void onUpdate(Location oldLoc, long oldTime, Location newLoc, long newTime);
}
public void start();
public void start(LocationUpdateListener update);
public void stop();
public boolean hasLocation();
public boolean hasPossiblyStaleLocation();
public Location getLocation();
public Location getPossiblyStaleLocation();
}
ProviderLocationTracker.java
package com.gabesechan.android.reusable.location;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
public class ProviderLocationTracker implements LocationListener, LocationTracker {
// The minimum distance to change Updates in meters
private static final long MIN_UPDATE_DISTANCE = 10;
// The minimum time between updates in milliseconds
private static final long MIN_UPDATE_TIME = 1000 * 60;
private LocationManager lm;
public enum ProviderType{
NETWORK,
GPS
};
private String provider;
private Location lastLocation;
private long lastTime;
private boolean isRunning;
private LocationUpdateListener listener;
public ProviderLocationTracker(Context context, ProviderType type) {
lm = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
if(type == ProviderType.NETWORK){
provider = LocationManager.NETWORK_PROVIDER;
}
else{
provider = LocationManager.GPS_PROVIDER;
}
}
public void start(){
if(isRunning){
//Already running, do nothing
return;
}
//The provider is on, so start getting updates. Update current location
isRunning = true;
lm.requestLocationUpdates(provider, MIN_UPDATE_TIME, MIN_UPDATE_DISTANCE, this);
lastLocation = null;
lastTime = 0;
return;
}
public void start(LocationUpdateListener update) {
start();
listener = update;
}
public void stop(){
if(isRunning){
lm.removeUpdates(this);
isRunning = false;
listener = null;
}
}
public boolean hasLocation(){
if(lastLocation == null){
return false;
}
if(System.currentTimeMillis() - lastTime > 5 * MIN_UPDATE_TIME){
return false; //stale
}
return true;
}
public boolean hasPossiblyStaleLocation(){
if(lastLocation != null){
return true;
}
return lm.getLastKnownLocation(provider)!= null;
}
public Location getLocation(){
if(lastLocation == null){
return null;
}
if(System.currentTimeMillis() - lastTime > 5 * MIN_UPDATE_TIME){
return null; //stale
}
return lastLocation;
}
public Location getPossiblyStaleLocation(){
if(lastLocation != null){
return lastLocation;
}
return lm.getLastKnownLocation(provider);
}
public void onLocationChanged(Location newLoc) {
long now = System.currentTimeMillis();
if(listener != null){
listener.onUpdate(lastLocation, lastTime, newLoc, now);
}
lastLocation = newLoc;
lastTime = now;
}
public void onProviderDisabled(String arg0) {
}
public void onProviderEnabled(String arg0) {
}
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
}
}
FallbackLocationTracker.java
package com.gabesechan.android.reusable.location;
import android.content.Context;
import android.location.Location;
import android.location.LocationManager;
public class FallbackLocationTracker implements LocationTracker, LocationTracker.LocationUpdateListener {
private boolean isRunning;
private ProviderLocationTracker gps;
private ProviderLocationTracker net;
private LocationUpdateListener listener;
Location lastLoc;
long lastTime;
public FallbackLocationTracker(Context context, ProviderLocationTracker.ProviderType type) {
gps = new ProviderLocationTracker(context, ProviderLocationTracker.ProviderType.GPS);
net = new ProviderLocationTracker(context, ProviderLocationTracker.ProviderType.NETWORK);
}
public void start(){
if(isRunning){
//Already running, do nothing
return;
}
//Start both
gps.start(this);
net.start(this);
isRunning = true;
}
public void start(LocationUpdateListener update) {
start();
listener = update;
}
public void stop(){
if(isRunning){
gps.stop();
net.stop();
isRunning = false;
listener = null;
}
}
public boolean hasLocation(){
//If either has a location, use it
return gps.hasLocation() || net.hasLocation();
}
public boolean hasPossiblyStaleLocation(){
//If either has a location, use it
return gps.hasPossiblyStaleLocation() || net.hasPossiblyStaleLocation();
}
public Location getLocation(){
Location ret = gps.getLocation();
if(ret == null){
ret = net.getLocation();
}
return ret;
}
public Location getPossiblyStaleLocation(){
Location ret = gps.getPossiblyStaleLocation();
if(ret == null){
ret = net.getPossiblyStaleLocation();
}
return ret;
}
public void onUpdate(Location oldLoc, long oldTime, Location newLoc, long newTime) {
boolean update = false;
//We should update only if there is no last location, the provider is the same, or the provider is more accurate, or the old location is stale
if(lastLoc == null){
update = true;
}
else if(lastLoc != null && lastLoc.getProvider().equals(newLoc.getProvider())){
update = true;
}
else if(newLoc.getProvider().equals(LocationManager.GPS_PROVIDER)){
update = true;
}
else if (newTime - lastTime > 5 * 60 * 1000){
update = true;
}
if(update){
lastLoc = newLoc;
lastTime = newTime;
if(listener != null){
listener.onUpdate(lastLoc, lastTime, newLoc, newTime);
}
}
}
}
The interface defines a generic location tracker so you can switch between them. ProviderLocationTracker will allow you to track via GPS or network, depending on the parameter you pass to its constructor. FallbackLocationTracker will track via both, giving you only the most accurate info currently available but falling back to network if GPS isn't ready.
use this code
and implemets your activity from "implements LocationListener"
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,3000, // 3 sec
5, this);
boolean isGPS = locationManager.isProviderEnabled (LocationManager.GPS_PROVIDER);
if(!isGPS)
{
showSettingsAlert();
GPS_imageview.setBackgroundResource(R.drawable.gpsnonfix);
//Toast.makeText(getApplicationContext(), "Please Start GPS to get more Accurate location", Toast.LENGTH_SHORT) .show();
}
and use following also
#Override
public void onLocationChanged(Location location) {
int a=location.getExtras().getInt("satellites") ;
if(a>4)
{
String str = "Latitude: "+location.getLatitude()+" \nLongitude: "+location.getLongitude();
// Toast.makeText(getBaseContext(), str, Toast.LENGTH_LONG).show();
Double lat=location.getLatitude();
Double lan=location.getLongitude();
}else{
}
String str = "Latitude: "+location.getLatitude()+" \nLongitude: "+location.getLongitude();
Toast.makeText(getBaseContext(), str, Toast.LENGTH_LONG).show();
}
#Override
public void onProviderDisabled(String provider) {
/******** Called when User off Gps *********/
Latitude="0.0";
Longitude="0.0";
Toast.makeText(getBaseContext(), "Gps turned off ", Toast.LENGTH_LONG).show();
}
#Override
public void onProviderEnabled(String provider) {
/******** Called when User on Gps *********/
Toast.makeText(getBaseContext(), "Gps turned on ", Toast.LENGTH_LONG).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
This code get no of sattelite .if no of sattelite is greter than 4 then get proper result..thats accuracy of result is good...
When you start your app, your GPS probably has not yet made connection and gives you a default location such as 0,0. If your phone finds its coordinates at a later point in time, your app has no way of detecting this.
This line:
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
states that every time your phone discovers a change of location, the "OnLocationChanged"-method (of the object in which you called that line of code), is called. As far as I can see, you did not implement this method yet.
I suggest the following. Change your third line to:
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, gpsTracker);
So it uses the implementation of the onLocationChanged method of your gpsTracker.
Now, implement the OnLocationChanged-method of the GPSTracker-class which you already defined, but not yet implemented:
#Override
public void onLocationChanged(Location location) {
//This method is triggered every time your location changes.
//The 'location' argument can be used to access the current location.
}

Categories

Resources