2010-08-20 46 views
4

我仍在使用基於位置的鬧鐘android應用程序。我有一個AlarmService類,用於啓動通知和接近警報。我開始這項服務:如何停止Android服務的多個實例?

startService(intentAlarmService); 

我嘗試使用停止服務:

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

這是發生了什麼:該服務停止,但後來,當我開始在服務的另一實例(即退出應用程序,啓動應用程序,啓動服務) - 我發現(通過Toasts)服務的先前實例仍在運行。例如,在AlarmService類中,有一個帶有onLocationChanged方法的LocationListener。因此,在這種方法中,我提出:

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

當我重新啓動該服務,敬酒不斷顯示出來與前AlarmTitles,和當前AlarmTitle。

因此,當我嘗試停止AlarmService時,有些東西不起作用 - 這可能是什麼?

注意:當我重新安裝應用程序時,服務停止。然後,當我開始服務時,只有當前的鬧鐘顯示在吐司(我希望每次都會發生這種情況)。

我的服務有問題。任何想法我可以做什麼?

謝謝。


代碼我的應用程序:

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

回答

6

我發現(通過乾杯),該服務的以前的實例仍在運行。

我的猜測是,你正在泄漏的服務,可能是無法調用removeUpdates()脫離你的LocationListener。從Android生命週期的角度來看,只有一個真正運行的服務副本,但是你正在阻止其他服務被垃圾收集。

此外,請用this替換出現的所有出現的getApplicationContext()

+0

我還是有點新到Android編程。我知道什麼是內存泄漏,但是「泄漏服務」是什麼意思?你能否提供一些關於我的應用程序出現問題的更多解釋? 謝謝,我對getApplicationContext()的出現感到抱歉。 – 2010-08-20 04:00:51

+0

@Yasir Malang:我相信你正在調用'registerLocationUpdates()'而不是調用'removeUpdates()'。 – CommonsWare 2010-08-20 04:16:24

+0

謝謝你的幫助。我查看了我的代碼,發現了3個單獨的LocationListener類的實現。我這樣做是因爲我不知道如何從另一個班級訪問1個公共班級。你將如何編寫代碼來創建1個公共LocationListener類,然後讓其他類繼承它? – 2010-08-20 20:34:17

0

測試:

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

    } 
}