How to stop multiple instances of an Android service?

I am still working on my Android software for Android. I have an AlarmService class that fires notifications and proximity notifications. I start this service with:

startService(intentAlarmService); 

I am trying to stop the service using:

 Intent intentAlarmService = new Intent(this, AlarmService.class); stopService(intentAlarmService); 

Here's what happens: the service stops, but then when I start another instance of the service (i.e. exit the application, launch the application, start the service), I discover (through Toasts) that the previous instances of the service are still working. For example, in the AlarmService class, there is a LocationListener with the onLocationChanged method. So, in this method I set:

 Toast.makeText(AlarmService.this, "AlarmTitle: " + mAlarmTitle, Toast.LENGTH_SHORT).show(); 

And when I start the service again, the toasts continue to display with previous alarms and the current type of AlarmTitle.

So, something does not work when I try to stop the AlarmService - what could it be?

Note: when you reinstall the application, the service stops working. Then, when I start the service, only the current AlarmTitle is displayed in Toast (I want this to happen every time).

Something is wrong with my service. Any ideas what I can do?

thanks.


CODE FROM MY APPLICATIONS:

 public void onDestroy() { super.onDestroy(); Intent alarmIntent = new Intent(getApplicationContext(), AlarmReceiver.class); PendingIntent pendingIntentAlarm = PendingIntent.getBroadcast(getApplicationContext(), PENDING_INTENT_REQUEST_CODE1, alarmIntent, PendingIntent.FLAG_CANCEL_CURRENT); pendingIntentAlarm.cancel(); Intent intentAlarmService = new Intent(getApplicationContext(), AlarmService.class); stopService(intentAlarmService); mNtf.cancel(NOTIFICATION_ID1); mNtf.cancelAll(); } 
+4
source share
2 answers

I discover (through Toasts) that previous instances of the service are still running.

I assume that you experience a service leak, perhaps without calling removeUpdates() to disconnect your LocationListener . There is only one real working copy of the service (in terms of the Android life cycle), but you prevent the collection of other garbage through a leak.

Also, replace all occurrences of getApplicationContext() with this .

+6
source

check this:

 private Boolean Tb = true; if(condition) { if(Tb) { Toast.makeText(getApplicationContext(),"content...", Toast.LENGTH_LONG).show(); } Tb =false; final Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { Tb =true; } }, Toast.LENGTH_LONG); } } 
0
source

All Articles