stopService non smette di essere il mio servizio … perché?
ho un servizio di background sul mio APP android che sta ottenendo la mia posizione GPS e l'invio a un db remoto. Funziona bene.
Il problema è quando voglio fermare il servizio …. non si ferma: S. Anche nessuna exception o errori su logcat sono apparse … semplicemente non si ferma.
questo è il codice per avviare il mio srvice (con un button):
startService(new Intent(GPSLoc.this, MyService.class)); //enciendo el service
questo è il codice in cui lo interrompo (sul metodo onactivityresult):
stopService(new Intent(GPSLoc.this, MyService.class));
Sono stato eseguito il debug dell'applicazione e ho verificato che la codeline stopService è stata chiamata each volta che ho debuggato, ma non si ferma ……
sono sicuro che non è causa di arresto nel database ho ancora recuperare posizioni GPS dall'emulatore quando ho premuto il button per interrompere il servizio.
cosa sto facendo male?
10 Solutions collect form web for “stopService non smette di essere il mio servizio … perché?”
Avete implementato onDestroy()
? Se no, credo che questa potrebbe essere la soluzione – e si interrompe il Timer
o qualsiasi altra cosa che utilizzi per eseguire il servizio in onDestroy()
.
Un servizio può essere arrestato chiamando il metodo stopSelf () o chiamando Context.stopService ().
Vedi questo link per ulteriori informazioni.
sono sicuro che non è causa di arresto nel database ho ancora recuperare posizioni GPS dall'emulatore quando ho premuto il button per interrompere il servizio.
Probabilmente non stai annullando la logging di LocationListener
.
Ho avuto lo stesso problema. Ho scoperto che se il servizio ha collegato GoogleApiClient
e che ha ancora l'aggiornamento della posizione, stopService()
ha alcun effetto, l'industria del servizio () non è stata chiamata. Per risolvere il problema, ho creato una function per arrestare il servizio di localizzazione nel codice di servizio. Chiamare stopLocationService()
dall'attività e quindi call stopService. Ecco l'esempio del codice:
public class myLocationService extends Service{ ... public void stopLocationUpdates() { LocationService.FusedLocationApi.removeLocationUpdates(mGoogleApiClient,this); mGoogleApiClient.disconnect(); } ... }
Nell'attività,
{ ... if(mService != null && isBound) { mService.stopLocationUpdates(); doUnbindService(); stopService(new Intent(this, myLocationService.class)); } ... }
È molto comune questa situazione in cui ho bisogno di interrompere il mio servizio prima di finire il process. In alcuni casi non è sufficiente con stopService (intento). Dovresti avere in mente l'implementazione onDestroy () nel mio servizio. Esempio:
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(); } }
In questo modo, quando si è arrestato il servizio utilizzando il metodo stopService si avrà anche interrotto il contatore di process.
public void stopService(){ context.stopService(intent); LocalBroadcastManager.getInstance(context).unregisterReceiver(responseReceiver); responseReceiver = null; intent = null; }
Stai attento! @yaircarreno
Se stai monitorando la posizione GPS, probabilmente hai usato GoogleApiClient
.
Il concetto è che il servizio NON si fermerà,
se un'istanza GoogleApiClient
è ancora connessa.
(O qualsiasi altro problema che deve essere prima distrutto / non registrato)
Per far funzionare, implementa onDestroy()
all'interno del tuo servizio:
@Override public void onDestroy() { // Unregistered or disconnect what you need to // For example: mGoogleApiClient.disconnect(); super.onDestroy(); }
forse potrebbe essere che si crea una nuova intenzione each volta che si chiama il servizio di arresto.
stopService(new Intent(GPSLoc.this, MyService.class));
forse provare:
Intent intnet = new Intent(GPSLoc.this, MyService.class); // create el service startService(intenet); stopService(intent);
Per coloro che vogliono submit periodicamente una richiesta al server, questa è la mia soluzione. Dovresti avere questo nella tua attività o attività di frammento
{ 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); } }
il mio problema è stato risolto eliminando le viste aggiunte a WindowManager
ondestroy
public void onDestroy() { isRunning = false; super.onDestroy(); if (checkBox!=null) { windowManager.removeView(getlayoutparm(fabsetting,fabrateus,fabexit,true)); windowManager.removeView(checkBox); } }
Nel mio caso la stopService
viene chiamata con startService
quasi simultaneamente, quindi non c'è nessun servizio da fermarsi. Provare il stopService
ritardo per alcuni secondi. 🙂
@Override
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); } } } }