I cannot stop my service (update my location) in my Android app!

I implemented a Service that updates the current location and sends it to my Server. I use only ToggleButton: startService () to call the service and stopService () to stop it. I saw on logCat that the service continues to work after stopService is called, because when I restart the service, it updates two times (three ... or four ...) of my location.

My code is:

Service: Geolocalisation.java

public class Geolocalisation extends Service{

private LocationManager locationManager;
//private String locationProvider = LocationManager.NETWORK_PROVIDER;
private String locationProvider = LocationManager.NETWORK_PROVIDER;

@Override
public void onCreate(){

    System.out.println("Service en cours !!");

    //Recuperation Location
    String locationContext = Context.LOCATION_SERVICE;
    locationManager = (LocationManager) getSystemService(locationContext);
    if (locationManager != null && locationProvider != null) {

        majCoordonnes();
        locationManager.requestLocationUpdates(locationProvider, 10000, 0, new MajListener());

    }

}

@Override
public void onStart(Intent intent, int StartId){
    System.out.println("Service commence !!");
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
    SharedPreferences.Editor editor = preferences.edit();
    editor.putBoolean("geo", true);
    editor.commit();    
}

@Override
public void onDestroy(){
    System.out.println("Service détruit !!");
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
    SharedPreferences.Editor editor = preferences.edit();
    editor.putBoolean("geo", false);
    editor.commit();    

}

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


public void majCoordonnes() {
    StringBuilder stringBuilder = new StringBuilder("Fournisseur :");
    stringBuilder.append("\n");
    stringBuilder.append(locationProvider);
    stringBuilder.append(" : ");
    Location location = locationManager.getLastKnownLocation(locationProvider);

    if (location != null) {

        double latitude = location.getLatitude();
        double longitude = location.getLongitude();

        String lat = String.valueOf(latitude);
        String lon = String.valueOf(longitude);

        stringBuilder.append(latitude);
        stringBuilder.append(", ");
        stringBuilder.append(longitude);

        //Send location to server
        new sendLocation().execute(lat, lon);

        System.out.println("Localisation:  "+ lat +" "+lon );


    } else {
        stringBuilder.append("Non déterminée");
    }
    //Log.d("MaPositionMaj", stringBuilder.toString());
}


/**
 * Ecouteur utilisé pour les mises à jour des coordonnées
 */
class MajListener implements android.location.LocationListener {

    public void onLocationChanged(Location location) {
        majCoordonnes();
        System.out.println("Update geo!");
    }
    public void onProviderDisabled(String provider){
    }
    public void onProviderEnabled(String provider){
    }
    public void onStatusChanged(String provider, int status, Bundle extras){
    }
};

My Main.java, which calls and destroys the ToggleButton service:

intentGeo = new Intent().setClass(this,Geolocalisation.class);

    Boolean boolLog = preferences.getBoolean("geo", false);

    final ToggleButton toggleAge = (ToggleButton) findViewById(R.id.ToggleGeo);

    //Check ToggleButton if the service is already running
    if( boolLog != true){
        try{
            toggleAge.setChecked(false);

        }catch (Exception e){
            System.out.println("Service Error");
        }       
    } else {
        toggleAge.setChecked(true);
    }

    //Activer ou désactivé le service de géolocalisation
    toggleAge.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            // Perform action on clicks
            if (toggleAge.isChecked()) {

                try{
                    startService(intentGeo);
                    System.out.println("Turn ON");
                }catch (Exception e){
                    System.out.println("Service Error");
                }

            } else {

                try{
                    stopService(intentGeo);
                    System.out.println("Turn OFF");
                }catch (Exception e){
                    System.out.println("Service Error");
                }
            }
        }
    });

Thank you for your help!

PS I use Sharedpreference to determine if the service is running or not. But if the service fails, it will cause a problem. How to check the status of my service?

+3
3

. , , / .

, - , , onCreate:

Intent serviceIntent = new Intent();
serviceIntent.setClass(this, YourService.class);
bindService(serviceIntent, connection, Context.BIND_AUTO_CREATE);

, , . , , .

, !

unbindService(connection);
+2

onDestroy Geolocalisation.java , , , . , .

locationManager.removeUpdates(locationProvider);

.

+1

To stop updating the server, perhaps you should overwrite the function stopServicewith a stop code?

@Override
public stopService(Intent service)
{
    super.stopService();
    // code to stop updating server
}
0
source

Source: https://habr.com/ru/post/1796151/


All Articles