1

I am developing an application that is highly dependent on user location and geo fencing. I am trying to get the user location first and based on that further operations are carried out. Everything is working fine except for the fact that, some times I am getting wrong location values and unless and until I restart the app and in some cases, restart the phone, I don't get the correct value. I will post my Location Api codes below. If any changes required, please do let me know.

       manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    statusOfGPS = manager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    buildGoogleApiClient();
    if (!statusOfGPS) {
        displayPromptForEnablingGPS(this);

    } else {
        permissionAndLocationAccess();
    }
 @Override
public void onConnected(@Nullable Bundle bundle) {

    mLocationRequest = LocationRequest.create();
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    // Update location every second
    if (ActivityCompat.checkSelfPermission(this, ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(this, ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

    } else {
        ProgressUtil.hideProgressDialog(prgd_progressDialog);
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
        mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
                mGoogleApiClient);
        if (mLastLocation != null) {
            lat = mLastLocation.getLatitude();
            lon = mLastLocation.getLongitude();
            Log.e("Lat and Lng", "onconn");
            if (!String.valueOf(lat).equals("0.0")) {
                latitudeVal = mLastLocation.getLatitude();
                longitudeVal = mLastLocation.getLongitude();
                sendLatLong(latitudeVal, longitudeVal);
                Log.d("Lat and Lng", "in last loc");
                Log.d("Lat and Lng", String.valueOf(latitudeVal) + longitudeVal);
                new AsyncCaller().execute();

            }
        }
    }
}
 @Override
public void onLocationChanged(Location location) {
    if (location != null) {
        lat = location.getLatitude();
        lon = location.getLongitude();
        Log.e("Lat and Lng", "onchanged");
        if (!String.valueOf(lat).equals("0.0")) {
            latitudeVal = location.getLatitude();
            longitudeVal = location.getLongitude();
            ProgressUtil.hideProgressDialog(prgd_progressDialog);
            Log.e("Lat and Lng", "onchanged0");
            Log.e("Lat and Lng", String.valueOf(latitudeVal) + longitudeVal);
Hemant Parmar
  • 3,924
  • 7
  • 25
  • 49
Animesh Jena
  • 1,541
  • 1
  • 25
  • 44

1 Answers1

0

I am also using this class and in my case its working fine. You can check

public class BackgroundLocationService extends Service implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {

protected static final String TAG = "BackService";

public static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = GLOBAL_BACKGROUND_CHECK_TIME;
public GoogleApiClient mGoogleApiClient;
public LocationRequest mLocationRequest;
private PendingIntent mPendingIntent;
IBinder mBinder = new LocalBinder();

private class LocalBinder extends Binder {
    public BackgroundLocationService getServerInstance() {
        return BackgroundLocationService.this;
    }
}

@Override
public void onCreate() {
    super.onCreate();
    Log.i(TAG, "onCreate()");

    Intent mIntentService = new Intent(this, LocationUpdates.class);
    mPendingIntent = PendingIntent.getService(this, 1, mIntentService, PendingIntent.FLAG_UPDATE_CURRENT);
    buildGoogleApiClient();
}

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

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    super.onStartCommand(intent, flags, startId);

    if (mGoogleApiClient.isConnected()) {
        Log.i(TAG + " onStartCmd", "Connected");
        return START_STICKY;
    }

    if (!mGoogleApiClient.isConnected() || !mGoogleApiClient.isConnecting()) {
        Log.i(TAG + " onStartCmd", "GoogleApiClient not Connected");
        mGoogleApiClient.connect();
    }
    NotificationManager notificationManager = (NotificationManager) this.getSystemService(NOTIFICATION_SERVICE);
    NotificationCompat.Builder notification = new NotificationCompat.Builder(this);

    notification.setContentTitle("Title ");
    notification.setContentText("\n Tracking BackGround ... ");
    notification.setSmallIcon(R.drawable.big_marker);
    notificationManager.notify(151458461, notification.build());


    return START_STICKY;
}

protected synchronized void buildGoogleApiClient() {
    Log.i(TAG, "Building GoogleApiClient");
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
    mGoogleApiClient.connect();
    createLocationRequest();
}

protected void createLocationRequest() {
    Log.i(TAG, "createLocationRequest()");
    mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(GLOBAL_BACKGROUND_CHECK_TIME);
    mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);


}

protected void startLocationUpdates() {
    Log.i(TAG, "Started Location Updates");
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        return;
    }
    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, mPendingIntent);
}

public void stopLocationUpdates() {
    Log.i(TAG, "Stopped Location Updates");
    LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, mPendingIntent);
}

@Override
public void onConnected(Bundle connectionHint) {
    Log.i(TAG, "Connected to GoogleApiClient");
    startLocationUpdates();
}

@Override
public void onLocationChanged(Location location) {

    String message = "Latitude : " + location.getLatitude() + "\n Longitude : " + location.getLongitude() +
            "\n location Accuracy: " + location.getAccuracy() + "\n speed: " + location.getSpeed();
    Log.d(TAG, "onLocationChanged: " + message);
}

@Override
public void onConnectionSuspended(int cause) {
    Log.i(TAG, "Connection suspended");
    mGoogleApiClient.connect();
}

@Override
public void onConnectionFailed(@NonNull ConnectionResult result) {
    Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + result.getErrorCode());
}

@Override
public void onDestroy() {
    super.onDestroy();
    stopLocationUpdates();

}

}

coder_baba
  • 447
  • 3
  • 21