StopService no deja de ser mi servicio … ¿por qué?

Tengo un servicio de fondo en mi Android APP que está recibiendo mi posición GPS y enviarlo a un db remoto. Funciona bien.

El problema es cuando quiero parar el servicio …. no se detiene: S. También no se han producido excepciones o errores en logcat … simplemente no se detiene.

Este es el código para iniciar mi srvice (con un botón):

startService(new Intent(GPSLoc.this, MyService.class)); //enciendo el service 

Este es el código donde lo detengo (en el método onactivityresult):

 stopService(new Intent(GPSLoc.this, MyService.class)); 

He sido depurado de la aplicación, y he comprobado que la línea de stopService se ha llamado cada vez que depuré, pero no se detiene ……

Estoy seguro de que no se detiene la causa en mi base de datos todavía recive posiciones gps desde el emulador cuando tengo presionar el botón para detener el servicio.

Lo que estoy haciendo mal

¿Ha implementado onDestroy() ? Si no, creo que podría ser la solución – y se detiene su Timer o lo que está utilizando para ejecutar el servicio dentro onDestroy() .

Se puede detener un servicio llamando a su método stopSelf () o llamando a Context.stopService ().

Consulte este enlace para obtener más información.

Estoy seguro de que no se detiene la causa en mi base de datos todavía recive posiciones gps desde el emulador cuando tengo presionar el botón para detener el servicio.

Probablemente no cancele el registro de su LocationListener .

Es muy común esta situación donde necesito parar mi servicio antes de terminar el proceso. En algunos casos no es suficiente con stopService (intención). Debería tener en cuenta el implemento onDestroy () en mi servicio. Ejemplo:

 public class MyIntentService extends IntentService { // Defines and instantiates an object for handling status updates. private BroadcastNotifier mBroadcaster = null; private int progress = 0; //THIS IS MY COUNTER FOR EXAMPLE!!! public MyIntentService() { super("MyIntentService"); } @Override protected void onHandleIntent(Intent intent) { progress = 0; int tiempo_disponible = intent.getIntExtra("minutos_disponible", 0); if (mBroadcaster == null){ mBroadcaster = new BroadcastNotifier(this); } // Broadcasts an Intent indicating that processing has started. mBroadcaster.broadcastIntentWithState(Constants.STATE_ACTION_STARTED); mBroadcaster.broadcastIntentWithState(Constants.STATE_ACTION_RUNNING); while (progress < tiempo_disponible) { progress++; try { Log.i(Constants.TAG, "Procesing " + progress); mBroadcaster.notifyProgress(progress); Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // Reports that the feed retrieval is complete. mBroadcaster.broadcastIntentWithState(Constants.STATE_ACTION_COMPLETE); } @Override public void onDestroy() { progress = 1000000; // WHITH THAT YOU FINISH THE CICLE IF tiempo_disponible NEVER IS MAYOR THAT 1000000, YOU CAN USE OTHER CONDITIONAL!!!!!! super.onDestroy(); } } 

De esta forma, cuando haya detenido el servicio utilizando el método stopService también habrá detenido el contador de proceso o.

 public void stopService(){ context.stopService(intent); LocalBroadcastManager.getInstance(context).unregisterReceiver(responseReceiver); responseReceiver = null; intent = null; } 

¡Cuídate! @yaircarreno

Yo tuve el mismo problema. Encontré que si el servicio tiene GoogleApiClient conectado y aún consigue la actualización de la localización, el stopService() tiene ningún efecto, la industria del servicio () no fue llamada. Para solucionar el problema, he creado una función para detener el servicio de ubicación en el código de servicio. Llame al stopLocationService() de la actividad y, a continuación, llame a stopService. Aquí está el ejemplo de código:

 public class myLocationService extends Service{ ... public void stopLocationUpdates() { LocationService.FusedLocationApi.removeLocationUpdates(mGoogleApiClient,this); mGoogleApiClient.disconnect(); } ... } 

En actividad,

 { ... if(mService != null && isBound) { mService.stopLocationUpdates(); doUnbindService(); stopService(new Intent(this, myLocationService.class)); } ... } 

Podría ser quizás que usted está creando un nuevo Intent cada vez que usted llama el servicio de la parada.

 stopService(new Intent(GPSLoc.this, MyService.class)); 

Quizás intente:

 Intent intnet = new Intent(GPSLoc.this, MyService.class); // create el service startService(intenet); stopService(intent); 

Para aquellos que quieren enviar una solicitud al servidor periódicamente, esta es mi solución. Debe tener esto en su Actividad o Actividad de Fragmento

 { private static final Long UPDATE_LOCATION_TIME = 30 * 60 * 1000l; // 30 minute private AlarmManager alarm; private PendingIntent pIntent; ... @Override protected void onResume() { super.onResume(); // Run background service in order to update users location startUserLocationService(); Log.e(TAG, "onResume"); } @Override protected void onStop() { super.onStop(); stopUserLocationService(); Log.e(TAG, "onStop"); } private void startUserLocationService() { Log.i(TAG, "Starting service..."); Intent intent = new Intent(MainFragmentHolder.this, ServiceUserLocation.class); pIntent = PendingIntent.getService(this, 0, intent, 0); alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE); Calendar cal = Calendar.getInstance(); alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), UPDATE_LOCATION_TIME, pIntent); } private void stopUserLocationService() { alarm.cancel(pIntent); Intent intent = new Intent(MainFragmentHolder.this, ServiceUserLocation.class); stopService(intent); } } 

Si está realizando un seguimiento de la ubicación GPS, probablemente utilizó GoogleApiClient .

El concepto es que el Servicio NO se detendrá,

Si una instancia de GoogleApiClient todavía está conectada dentro de ella.

(O cualquier otro problema que deba ser destruido / no registrado en primer lugar)

Así que para que funcione, implemente onDestroy() dentro de su servicio:

 @Override public void onDestroy() { // Unregistered or disconnect what you need to // For example: mGoogleApiClient.disconnect(); super.onDestroy(); } 

Mi problema resuelto mediante la eliminación de las vistas añadidas a WindowManager ondestroy

 public void onDestroy() { isRunning = false; super.onDestroy(); if (checkBox!=null) { windowManager.removeView(getlayoutparm(fabsetting,fabrateus,fabexit,true)); windowManager.removeView(checkBox); } } 

En mi caso el stopService se llama con startService casi simultáneamente así que ningún servicio está allí para ser parado. Intente retrasar stopService durante unos segundos. 🙂

@Anular

 public void onDestroy() { Log.d(TAG, "onDestroy"); super.onDestroy(); if (mLocationManager != null) { for (int i = 0; i < mLocationListeners.length; i++) { try { mLocationManager.removeUpdates(mLocationListeners[i]); } catch (Exception ex) { Log.d(TAG, "fail to remove location listners, ignore", ex); } } } } 
  • Error "No se puede iniciar el servicio de intención" al iniciar el servicio desde una actividad en Android
  • Proporcionar un servicio de fondo para otras aplicaciones
  • Android startService Synchronous?
  • ¿Por qué no funciona LocalBroadcastManager en lugar de Context.registerReceiver?
  • Reiniciar los servicios muertos (detenidos por los asesinos de tareas) en android como Whatsapp
  • Android: Pasar variables a un servicio ya en ejecución
  • ¿Debo usar PendingIntent.getService () o getBroadcast con AlarmManager?
  • El servicio android se reinicia en la aplicación matado
  • Paho MqttAndroidClient.connect siempre falla
  • Cómo detener / iniciar un servicio que contiene un bucle infinito en la creación
  • Null intent redelivered to Service onStartCommand ()
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.