1

I am using fusedlocation api in a Service for updating gps location to server every few seconds.In the MainActivity I have written the code to open locationSettings.Then in onResume method I start the Service(GpsService.java).The Service class send Broadcast everytime location is updated and it is received in the onResume() method.But I only get the location coordinates once.sendAmblnceGps() method is where the location is send to the server.

GpsService.java:

public class GpsService extends Service implements GoogleApiClient.OnConnectionFailedListener, GoogleApiClient.ConnectionCallbacks {
    com.google.android.gms.location.LocationListener locationListener;
    LocationRequest mLocationRequest;
    private static final long INTERVAL = 100* 50;
    private static final long FASTEST_INTERVAL = 100 * 20;
    GoogleApiClient googleApiClient;
    boolean connected;


    public GpsService() {

        super();
    }

    @Override
    public void onCreate() {
        super.onCreate();
        GoogleApiClient.Builder googleApiClientbuilder=new GoogleApiClient.Builder(GpsService.this).addConnectionCallbacks(GpsService.this).addOnConnectionFailedListener(GpsService.this).addApi(LocationServices.API);
        googleApiClient=googleApiClientbuilder.build();
        googleApiClient.connect();
        Toast.makeText(getApplicationContext(),"service created",Toast.LENGTH_SHORT).show();
    }

    protected void createLocationRequest() {
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(INTERVAL);
        mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        mLocationRequest.setSmallestDisplacement(100);
    }

    protected void startLocationUpdates() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, 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;
        }
                LocationServices.FusedLocationApi.requestLocationUpdates(
                googleApiClient, mLocationRequest,  locationListener);

        Log.d("TAG", "Location update started ..............: ");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e("Service Command", "Started");
        locationListener = new com.google.android.gms.location.LocationListener()
        {
            @Override
            public void onLocationChanged(Location location) {
                Intent intent = new Intent("location_updates");
                intent.putExtra("lat", location.getLatitude());
                intent.putExtra("longt", location.getLongitude());
                Log.e("location", "lat:" + " " + Double.toString(location.getLatitude()) + " " + "Longt:" + " " + Double.toString(location.getLongitude()));
                sendBroadcast(intent);
                } };
          return START_STICKY;

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient,locationListener);
        if(googleApiClient.isConnected()){
            googleApiClient.disconnect();
        }
        Log.e("Service","Stopped");

    }

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


    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
    Log.e("Connection failed","Service stopped");
        LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient,locationListener);
        if(googleApiClient.isConnected()){
            googleApiClient.disconnect();
        }
    }

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

    @Override
    public void onConnectionSuspended(int i) {
    Log.e("Connection","suspended");
    }

}

MainActivity.java:

@Override
    protected void onResume() {
        super.onResume();
        if (locationManager == null) {
            locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
            gps_enabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

        } else {
            gps_enabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
            if (isConnected()) {
                if (gps_enabled) {
                    progressDialog = new ProgressDialog(MainActivity.this);
                    progressDialog.setMessage("Acquiring your current location");
                    progressDialog.setIndeterminate(true);
                    progressDialog.getWindow().setGravity(Gravity.CENTER);
                    progressDialog.show();
                    Log.e("starting", "service");
                    intent = new Intent(MainActivity.this, GpsService.class);
                    startService(intent);
                    broadcastReceiver = new BroadcastReceiver() {
                        @Override
                        public void onReceive(Context context, Intent intent) {
                            Log.e("starting", "broadcastservice");
                            latitude = Double.toString(intent.getDoubleExtra("lat", 0.0));
                            longitude = Double.toString(intent.getDoubleExtra("longt", 0.0));
                            if (isConnected()) {
                                sendAmblnceGps();
                            } else {
                                progressDialog.cancel();
                                Toast.makeText(getApplicationContext(), "Please enable internet connection", Toast.LENGTH_SHORT).show();
                            }

                             }
                             };
                    Log.e("registering", "broadcastservice");
                    registerReceiver(broadcastReceiver, new IntentFilter("location_updates"));
                             }
                             }
                         else {
                   Toast.makeText(getApplicationContext(),"Enable Internet Connection",Toast.LENGTH_SHORT).show();
                             }
                            }
                             }
jobin
  • 1,489
  • 5
  • 27
  • 52

1 Answers1

0

You have specified mLocationRequest.setSmallestDisplacement(100);, so you need to move at least 100 meters from the location of the initial location update to have a new location update.

Markus Kauppinen
  • 3,025
  • 4
  • 20
  • 30
  • since i am getting gps location only once I delay for 5 secs after the first gps location is sent and again start the service. Is this a good way to do it – jobin Mar 25 '17 at 15:08
  • It might give you a new location update with roughly the same location. I haven't tried that. But what would be the the point? If you want location updates with smaller displacement than 100 meters, then change the value given in `mLocationRequest.setSmallestDisplacement()`. And if you then get location updates too often, change the value given in `mLocationRequest.setFastestInterval()`. – Markus Kauppinen Mar 25 '17 at 16:08