2012-08-10 68 views
0

我有一個廣播公司的Foregound服務。服務廣播公司/ Runnable不會停止

@Override 
public int onStartCommand(Intent intent, int flags, int startId) { 
    // Service 
    Log.d("Service","Service started"); 

    startTime = intent.getLongExtra("STARTTIME", 0); 
    endTime = intent.getLongExtra("ENDTIME", 0); 
    isRunning = true; 

    postNotification(); 

    // Broadcaster 
    handler.removeCallbacks(updateRunnable); 
    handler.postDelayed(updateRunnable, DELAY); 

    return START_STICKY; 
} 

當我試圖停止服務onDestroy()運行所有的罰款,但updateRunnable不斷會這麼廣播仍會發生。

private Runnable updateRunnable = new Runnable() { 
    public void run() { 

     Log.d("Service", "run");    
     currentTime = System.currentTimeMillis(); 

     if(endTime > 0 && (currentTime-startTime) >= endTime) { 
      isRunning = false; 

      // Alarm 
      AlarmNotification alarmNotification = new AlarmNotification(context); 
      alarmNotification.startAlarm(); 

      // Notification 
      AppNotification notify = new AppNotification(context); 
      notify.stopNotification(); 

      update(); 

      // Tried them all: 
      stopService(intentBroadcaster); 
      stopForeground(true); 
      stopSelf(); 
     } else { 
      update(); 
     } 
    handler.postDelayed(this, 1000); // 1 seconds 
    } 
}; 

正如你所看到的,我已經嘗試了所有我能想到的停止命令。我在這裏做錯了什麼?如何停止廣播/可運行?

回答

0

由於您的應用程序進程仍在運行,您的廣播服務器會繼續運行,因此您的線程將繼續執行,除非您告訴它不要。

可以很容易地阻止你的線程,運行中的方法:

private boolean shouldContinue = true; 
private Runnable updateRunnable = new Runnable() { 
    public void run(){ 
     // ... whaterver your doing 
     if(shouldContinue){ 
      handler.postDelayed(this, 1000); 
     } 
    } 
}; 

public void onDestroy(){ 
    shouldContinue = false; 
} 
+0

謝謝你,你真棒! – aelveborn 2012-08-10 02:14:37