0

I am trying to get location in app and when i turn GPS on for the very first time. It shows latitude and longitude 0,0. but when i check again it shows correctly. I am sharing my code with you please help me to find out where is the problem. this is my code for GPS tracker. I have tried many solutions but did not get anything working. What is the reason of getting o first time???

public class LocationTrack extends Service implements LocationListener {

private final Context mContext;


boolean checkGPS = false;


boolean checkNetwork = false;

boolean canGetLocation = false;

Location loc;
double latitude;
double longitude;


private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 70;


private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1;
protected LocationManager locationManager;

public LocationTrack(Context mContext) {
    this.mContext = mContext;
    getLocation();
}

private Location getLocation() {

    try {
        locationManager = (LocationManager) mContext
                .getSystemService(LOCATION_SERVICE);

        // get GPS status
        checkGPS = locationManager
                .isProviderEnabled(LocationManager.GPS_PROVIDER);

        // get network provider status
        checkNetwork = locationManager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (!checkGPS && !checkNetwork) {
            Toast.makeText(mContext, "No Service Provider is available", Toast.LENGTH_SHORT).show();
        } else {
            this.canGetLocation = true;

            // if GPS Enabled get lat/long using GPS Services
            if (checkGPS) {

                if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, 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.
                }
                locationManager.requestLocationUpdates(
                        LocationManager.GPS_PROVIDER,
                        MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                if (locationManager != null) {
                    loc = locationManager
                            .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                    if (loc != null) {
                        latitude = loc.getLatitude();
                        longitude = loc.getLongitude();
                    }
                }


            }


            if (checkNetwork) {


                if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, 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.
                }
                locationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER,
                        MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);

                if (locationManager != null) {
                    loc = locationManager
                            .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

                }

                if (loc != null) {
                    latitude = loc.getLatitude();
                    longitude = loc.getLongitude();
                }
            }

        }


    } catch (Exception e) {
        e.printStackTrace();
    }

    return loc;
}

public double getLongitude() {
    if (loc != null) {
        longitude = loc.getLongitude();
    }
    return longitude;
}

public double getLatitude() {
    if (loc != null) {
        latitude = loc.getLatitude();
    }
    return latitude;
}

public boolean canGetLocation() {
    return this.canGetLocation;
}

public void showSettingsAlert() {
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);


    alertDialog.setTitle("GPS is not Enabled!");

    alertDialog.setMessage("Do you want to turn on GPS?");


    alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            mContext.startActivity(intent);
        }
    });


    alertDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
        }
    });


    alertDialog.show();
}


public void stopListener() {
    if (locationManager != null) {

        if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, 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.removeUpdates(LocationTrack.this);
    }
}

@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public void onLocationChanged(Location location) {
    this.loc = location;
    getLatitude();
    getLongitude();

}

@Override
public void onStatusChanged(String s, int i, Bundle bundle) {

}

@Override
public void onProviderEnabled(String s) {

}

@Override
public void onProviderDisabled(String s) {

}

}

Manifest file with all permissions....

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.user.attendenceapplication">
<uses-feature android:name="android.hardware.location.gps" />

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

<application
    android:allowBackup="true"
    android:icon="@drawable/logodki"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".SplashScreen">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
  • `public LocationTrack(Context mContext)` ?? Please show how you create and start your service. It looks as if you do not use an intent to do so. It will not run as a service then. – greenapps Apr 30 '18 at 09:10
  • `public double getLongitude() {` ??? A service cannot have such public member functions. – greenapps Apr 30 '18 at 09:14
  • But it works fine. It gives 0,0 for first time . After that its gives correct location. So why is it happening ??? When i enable the location service and come back to the activity again by pressing phones back button it gives lat, long zero. Is there any solution to get correct Lat, Long for the first time also. – Gunjan Sharma May 01 '18 at 05:17
  • Maybe it works fine. But it is not running as a service. You could as wel remove `extends Service` and it would still run 'fine'. You did not even react on this service matter. Strange. – greenapps May 01 '18 at 08:27

2 Answers2

0

Many GPS receivers will return 0 when queried for latitude or longitude before they have a fix, it's nothing to do with your code.

See this question: GPS Intermediate Driver Constantly Return 0 0 LAT LNG

afarley
  • 781
  • 6
  • 26
  • But when i run my program before its was running exactly fine..after few modifications its not working ...There would be some reason for sure but don't know what is it ....can we do something in on Provider enabled??? – Gunjan Sharma Apr 30 '18 at 08:37
  • What could be the solution for this ??? I am calling method getLocation()in OnProviderEnabled. Is this correct approach ?? – Gunjan Sharma May 01 '18 at 04:25
  • There's a discussion here about registering for GPS status-change notifications. It sounds like this is the only way to know if GPS has a fix http://stackoverflow.com/questions/15453576/android-check-if-gps-is-searching-has-fix-or-is-not-in-use?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa – afarley May 01 '18 at 04:55
  • Is there any other way except this?? – Gunjan Sharma May 01 '18 at 05:32
  • 1. Not that I know of. 2. What's wrong with this solution? I can't really propose an alternative if I don't understand your goal. – afarley May 01 '18 at 15:43
0

Sorry for late reply. All are fine with your code. just do one small change as below:

set MIN_TIME_BW_UPDATES = 0 and set MIN_DISTANCE_CHANGE_FOR_UPDATES = 0

Renu Meena
  • 11
  • 2