Location Provider Sometimes returns Sydney location points

64 Views Asked by At

I am using GPS_location, it returns currect locations, but sometimes it gives me sydney location points, i have tried it with location provider,as well as fused location api. it occurs on some devices (i.e. nexus 5x with no sim-card)

I've tested this code on these devices :

  • Nexus3 (with no sim, android version 6.0.1) //not getting sydney location on this device
  • Nexus4 (with no sim, android version 5.1) //not getting sydney location on this device
  • MotoG4 (with sim, android version 7.0) //not getting sydney location on this device
  • Nexus 5x (with no sim , android version 7.0) //on this device i got sydney location

any help will be appriciated. I've used this code :

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;

public class GoogleLocationService {
    private GoogleServicesCallbacks callbacks = new GoogleServicesCallbacks();
    LocationUpdateListener locationUpdateListener;
    Context activity;
    protected GoogleApiClient mGoogleApiClient;
    protected LocationRequest mLocationRequest;

    public static final long UPDATE_INTERVAL_IN_MILLISECONDS = 30000;


    public GoogleLocationService(Context activity, LocationUpdateListener locationUpdateListener) {
        this.locationUpdateListener = locationUpdateListener;
        this.activity = activity;
        buildGoogleApiClient();
    }

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

    protected void createLocationRequest() {
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

    }

    private class GoogleServicesCallbacks implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {

        @Override
        public void onConnected(Bundle bundle) {
            startLocationUpdates();
        }

        @Override
        public void onConnectionSuspended(int i) {
            mGoogleApiClient.connect();
        }

        @Override
        public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

//            if (connectionResult.getErrorCode() == ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED) {
//                Toast.makeText(activity, "Google play service not updated", Toast.LENGTH_LONG).show();
//            }
            locationUpdateListener.cannotReceiveLocationUpdates();
        }

        @Override
        public void onLocationChanged(Location location) {
            locationUpdateListener.updateLocation(location);
//            if (location.hasAccuracy()) {
//                if (location.getAccuracy() < 30) {
//                    locationUpdateListener.updateLocation(location);
//                }
//            }
        }
    }

    private static boolean locationEnabled(Context context) {
        boolean gps_enabled = false;
        LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        try {
            gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return gps_enabled;
    }

    private boolean servicesConnected(Context context) {
        return isPackageInstalled(GooglePlayServicesUtil.GOOGLE_PLAY_STORE_PACKAGE, context);
    }

    private boolean isPackageInstalled(String packagename, Context context) {
        PackageManager pm = context.getPackageManager();
        try {
            pm.getPackageInfo(packagename, PackageManager.GET_ACTIVITIES);
            return true;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return false;
        }
    }


    public void startUpdates() {
    /*
     * Connect the client. Don't re-start any requests here; instead, wait
     * for onResume()
     */
        if (servicesConnected(activity)) {
            if (locationEnabled(activity)) {
                locationUpdateListener.canReceiveLocationUpdates();
                startLocationUpdates();
            } else {
                //locationUpdateListener.cannotReceiveLocationUpdates();
                locationUpdateListener.gpsNotEnabled();
                //Toast.makeText(activity, "Unable to get your location.Please turn on your device Gps", Toast.LENGTH_LONG).show();
            }
        } else {
            locationUpdateListener.cannotReceiveLocationUpdates();
            //Toast.makeText(activity, "Google play service not available", Toast.LENGTH_LONG).show();
        }
    }

    //stop location updates
    public void stopUpdates() {
        stopLocationUpdates();
    }

    //start location updates
    private void startLocationUpdates() {
        if (ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }

        if (mGoogleApiClient.isConnected()) {
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, callbacks);
        }
    }

    public void stopLocationUpdates() {
        if (mGoogleApiClient.isConnected()) {
            LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, callbacks);
        }
    }

    public void startGoogleApi() {
        mGoogleApiClient.connect();
    }

    public void closeGoogleApi() {
        mGoogleApiClient.disconnect();
    }
}

import android.location.Location;

public interface LocationUpdateListener {

    /**
     * Called immediately the service starts if the service can obtain location
     */
    void canReceiveLocationUpdates();

    /**
     * Called immediately the service tries to start if it cannot obtain location - eg the user has disabled wireless and
     */
    void cannotReceiveLocationUpdates();

    /**
     * Called whenever the location has changed (at least non-trivially)
     * @param location
     */
    void updateLocation(Location location);

    /**
     * Called when GoogleLocationServices detects that the device has moved to a new location.
     * @param localityName The name of the locality (somewhere below street but above area).
     */
    void updateLocationName(String localityName, Location location);

    void gpsNotEnabled();
}

import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity" ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        handler = new Handler();
        handler.post(locationTask);
    }

    GoogleLocationService googleLocationService;
    public final int THIRTY_SECONDS = 30 * 1000;

    private void prepareLocationReceiver(){
        googleLocationService = new GoogleLocationService(this, new LocationUpdateListener() {
            @Override
            public void canReceiveLocationUpdates() {
                Log.e(TAG,"canReceiveLocationUpdates");
                googleLocationService.stopLocationUpdates();
            }

            @Override
            public void cannotReceiveLocationUpdates() {
                Log.e(TAG,"cannotReceiveLocationUpdates");
                googleLocationService.stopLocationUpdates();
            }

            //update location to our servers for tracking purpose
            @Override
            public void updateLocation(android.location.Location location) {
                Log.e(TAG,"updateLocation");
                if (location != null ) {
                    //here sometimes i get sydney location, but many times it gives me proper location.
                    googleLocationService.stopLocationUpdates();
                }
            }

            @Override
            public void updateLocationName(String localityName, android.location.Location location) {
                Log.e(TAG,"updateLocationName");
                googleLocationService.stopLocationUpdates();
            }

            @Override
            public void gpsNotEnabled() {
                Log.e(TAG,"gpsNotEnabled");
                googleLocationService.stopLocationUpdates();
            }
        });
    }

    private Handler handler;

    private Runnable locationTask = new Runnable() {
        @Override
        public void run() {
            if(googleLocationService != null){
                googleLocationService.startUpdates();
            }else{
                prepareLocationReceiver();
            }
            handler.postDelayed(this, THIRTY_SECONDS);
        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (googleLocationService != null) {
            googleLocationService.stopLocationUpdates();
        }
    }
}
0

There are 0 best solutions below