I can't stop my Service (update my location) on my android app!
I've implemented a Service which update my current location and send it to my Server. I only use with a ToggleButton: startService() to call the service and stopService() to stop it. I've seen on the logCat that the service continue to run after calling stopService because when I restart the service, it update two time (three...or four..) my location.
My code:
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 whic开发者_开发知识库h call and destroy the service by ToggleButton:
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");
}
}
}
});
Thanks for your help !
PS I use Sharedpreference to determinate if Service is running or not. But if the service crash, it will occures a problem. How can I check the state of my Service?
You shouldn't need to start and stop the service yourself. You can bind your activity to the service and then use methods on your service to stop/start it.
To bind to a service, you need to use something like this from your activity, probably in onCreate:
Intent serviceIntent = new Intent();
serviceIntent.setClass(this, YourService.class);
bindService(serviceIntent, connection, Context.BIND_AUTO_CREATE);
There are some other boilerplate things you will need to do, described here. Once your activity is bound to the service, you can then stop and start it using methods on your service class via a concrete object reference.
Just be sure to unbind from the service when your activity is destroyed!
unbindService(connection);
In your onDestroy function from Geolocalisation.java you are not ending the Listener, you are simply changing the variable that your program checks to see if the service is running or not. You could add code here to stop the location listener from running any further.
locationManager.removeUpdates(locationProvider);
should do the trick.
To stop updating the server maybe you should overwrite the stopService
function with the stopping code?
@Override
public stopService(Intent service)
{
super.stopService();
// code to stop updating server
}
精彩评论