开发者

How to stop multiple instances of an Android Service?

I am still working on my location-based alarm android application. I 开发者_如何学Chave an AlarmService class that starts notifications and proximity alerts. I am starting this service with:

startService(intentAlarmService);

I try to stop the service using:

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

This is what happens: The service stops, but then, when I start another instance of the service (i.e. exit the app, launch the app, start the service) - I discover (through Toasts) that the previous instances of the service are still running. For example, in the AlarmService class, there is a LocationListener with the onLocationChanged method. So, in this method, I put:

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

And when I re-start the service, Toasts keep showing up with the previous AlarmTitles, and the current AlarmTitle.

So, something is not working when I try to stop the AlarmService - what could this be?

Note: when I re-install the application, the service stops for real. Then when I start the service, only the current AlarmTitle shows in the Toast (I want this to happen every time).

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

thanks.


CODE FROM MY APP:

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();  
}


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

My guess is that you are leaking services, probably by failing to call removeUpdates() to detach your LocationListener. There is only one true running copy of the service (from an Android lifecycle standpoint), but you are preventing the other services from being garbage collected through your leak.

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


test 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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜