2012-07-16 184 views
1

我正在運行Service使用AlarmManagerService運行正常,我正在手動停止Service(單擊Button),但我需要在某個時間(可能是10秒)後停止Service。我可以使用this.stopSelf();,但在特定時間後如何撥打this.stopSelf();安卓服務需要在某段時間後停止

回答

1

可能是您應該考慮使用IntentService?當沒有工作時它會停止,所以你不需要自己管理它的狀態。

+0

非常感謝Mr.Andrei Mankevich。 – Kabir 2012-07-16 12:46:53

1

使用postDelayed方法Handler內服務完成它。例如:

new Handler().postDelayed(new Runnable() { 
@Override 
    public void run() { 
     stopSelf(); 
    } 
}, 10000); //will stop service after 10 seconds 
+0

它顯示錯誤'方法postDelayed(新的Runnable(){},int)是未定義的類型Handler'。另一個錯誤是'新的Runnable(){}類型的方法run()必須覆蓋超類方法。 – Kabir 2012-07-16 12:28:51

+0

將您的代碼的一部分放在http://pastebin.com/並粘貼鏈接。讓我看看你是如何做到這一點的。 – waqaslam 2012-07-16 12:30:36

0
  1. 創建一個Intent開始Service。將action設置爲自定義操作,例如"com.yourapp.action.stopservice"
  2. 使用AlarmManager,啓動Intent以啓動Service(無論您現在在做什麼)。如果它已經在運行,它將被傳送到ServiceonStartCommand()
  3. onStartCommand(),檢查action傳入Intent。如果action.equals("com.yourapp.action.stopservice"),請使用this.stopSelf()停止Service
+0

謝謝aswin kumar.But我不明白你的做法。我只是需要停止服務一段時間後。有時我會打電話給'this.stopSelf()'。我想從'onCreate()'調用。 – Kabir 2012-07-16 12:16:28

+0

服務啓動後,onCreate將不會被調用。所有後續的調用將被傳遞給onStartCommand()。我建議你經歷一個服務的生命週期。 – 2012-07-16 12:43:36

+0

之間,由[Waqas](http://stackoverflow.com/users/966550/waqas)回答是一個更好的解決方案 – 2012-07-16 12:43:56

1

這可以很容易地使用timertimerTask一起完成。

我仍然不知道爲什麼沒有建議這個答案,而是提供的答案不提供直接和簡單的解決方案。

在服務子類,在全球創建這些(你可以創建他們不是全局的,但你可能會碰到的問題)

//TimerTask that will cause the run() runnable to happen. 
TimerTask myTask = new TimerTask() 
{ 
    public void run() 
    { 
     stopSelf(); 
    } 
}; 


//Timer that will make the runnable run. 
Timer myTimer = new Timer(); 

//the amount of time after which you want to stop the service 
private final long INTERVAL = 5000; // I choose 5 seconds 

現在裏面你的服務的onCreate(),請執行下列操作:

myTimer.schedule(myTask, INTERVAL);

這應該在5秒後停止服務。