Search code examples
javaandroidlocationlistener

Will onLocationChanged still get called even though it is not in the Service's onStart?


I have a Service that needs to get the user's location when they move. I haven't been able to figure out how to put onLocationChanged inside onStart, so I just put it outside. Will it still be called when the user moves? If not, how would I call it in onStart?

public class myService extends Service implements LocationListener {
Double lat;
Double lng;

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

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Let it continue running until it is stopped.
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();





return START_STICKY;

}

@Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();

}



@Override
public void onLocationChanged(Location location) {

if (MainActivity.location != null) {


   lat = MainActivity.location.getLatitude();

    lng = MainActivity.location.getLongitude();


    if (MainActivity.placeArrayList.size() != 0) {
        for (int i = 0; i < MainActivity.placeArrayList.size(); i++) {


            Log.e("hello", String.valueOf(Float.parseFloat(MainActivity.latitudeArrayList.get(i))));

            MainActivity.destination.setLatitude(Double.parseDouble(MainActivity.latitudeArrayList.get(i)));
            MainActivity.destination.setLongitude(Double.parseDouble(MainActivity.longitudeArrayList.get(i)));
            Log.e("distancemeters", String.valueOf(MainActivity.location.distanceTo(MainActivity.destination)));

            if (MainActivity.location.distanceTo(MainActivity.destination)<100) {




                AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

                audioManager.setStreamVolume(AudioManager.STREAM_RING, AudioManager.RINGER_MODE_SILENT, AudioManager.FLAG_SHOW_UI);


            } else {



            }

        }


    }
}

}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {

}

@Override
public void onProviderEnabled(String provider) {

}

@Override
public void onProviderDisabled(String provider) {

}
}

Solution

  • Assuming you are using Google's FusedLocationProviderApi, you need to do a couple of things first:

    1. Change your class to implement GoogleApiClient.ConnectionCallbacks and GoogleApiClient.OnConnectionFailedListener
    2. Create your GoogleApi object
    3. Create your LocationRequest object
    4. Register your class as a LocationListener

    First, change your class definition as follows:

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

    Then put this in your onStart() method:

    // 2. Create the GoogleApi object
    GoogleApi = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
    
    // 3. Create the LocationRequest
    mLocationRequest.setInterval(1000); // in milliseconds
    mLocationRequest.setFastestInterval(1000); // in milliseconds
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    
    // 4. Register your listener
    LocationServices.FusedLocationApi.requestLocationUpdates(GoogleApi, mLocationRequest, this)
    

    If you want to unregister your listener, put this in onDestroy():

    LocationServices.FusedLocationApi.removeLocationUpdates(GoogleApi, this);
    

    However, keep in mind that using this method means you will get a location update at specified time intervals, not when the user moves. You will need to find a way of keeping track of the user's location and determining a minimum distance which constitutes "movement". Also you will need to consider that the location might dance around the user's location so you will also have to take this into account.