2013-02-08 38 views
5

我做了一個遠程服務,這個服務是在我第一次啓動時通過我的活動啓動的,之後,如果服務啓動,活動總是會看起來避免再次啓動它。服務在onTaskRemoved後重新創建

該服務在onCreate函數中運行一些方法。此服務始終運行,並在啓動時啓動。

問題(不是一個大問題,但我想知道爲什麼)是,如果我停止我的活動創建服務,onTaskRemoved被調用,這是正確的,但幾秒鐘後,再次調用oncreate方法並且服務再次開始。

任何想法爲什麼?我怎樣才能控制這個?

<service 
     android:name=".Service" 
     android:icon="@drawable/ic_launcher" 
     android:label="@string/service_name" 
     android:process=":update_process" > 
</service> 

AndroidManifest.xml中

if (!isRunning()) { 
    Intent service = new Intent(this, UpdateService.class); 
    startService(service); 
} else { 
    //Just to debug, comment it later 
    Toast.makeText(this, "Service was running", Toast.LENGTH_SHORT).show(); 
} 

當如果它沒有運行

+0

我不清楚你的問題。但不要擔心服務的多個實例。從第二次調用['startService()'](http://developer.android.com/reference/android/content/Context.html#startService(android.content.Intent))不會啓動服務兩次,如果它已經在運行。 – 2013-02-08 11:55:47

+0

@LaiVung多重實例不是問題,問題在於活動停止後調用oncreate的方法,所以onCreate內部的方法再次被調用,我不想要。 – Marcel 2013-02-08 12:02:53

+0

你是否在你的活動結束時開始了一些事情(比如'onDestroy()')? – 2013-02-08 12:20:12

回答

8

的問題,該服務已啓動的是你的服務是每默認粘,這意味着它將在死亡後重新啓動,直到您明確要求停止。

覆蓋您的服務中的onStartCommand()方法,並讓它返回START_NOT_STICKY。那麼你的服務在遇難時將不會重新啓動。

@Override 
public int onStartCommand(Intent intent, int flags, int startId) 
{ 
    return START_NOT_STICKY; 
} 
+0

我已經解決了,這是如何,謝謝任何方式 – Marcel 2014-02-07 18:05:42

+1

@Marcel:現在其他人尋找這個問題的答案也可以看到解決方案:) – 2015-01-29 09:24:14

+0

開始不粘手一個很好的解決方案或onTaskRemoved。 – Minkoo 2017-03-04 08:01:05

6

雖然Bjarke的解決方案是有效的,我想提出覆蓋的地方可能需要進行的任何服務的情況下恢復的替代解決方案。

Android在重新啓動服務後再次調用onStartCommand()以通知您服務進程意外崩潰(因爲其任務堆棧已被刪除)並且正在重新啓動。

如果你看看onCreate()intent的說法,這將是null(僅適用於這樣的重新啓動),這表明Android是重新創建這些意外崩潰之前粘滯服務。

在某些情況下,僅針對此類重新啓動返回NON_STICKY是明智的做法,執行任何所需的清理/恢復並停止服務,以便您正常退出。

當服務正常啓動時,您仍然應該返回STICKY,否則您的服務將永遠不會重新啓動,以便您執行任何恢復。

@Override 
public int onStartCommand(Intent intent, int flags, int startId) 
{ 
    // intent is null only when the Service crashed previously 
    if (intent == null) { 
     cleanupAndStopServiceRightAway(); 
     return START_NOT_STICKY; 
    } 
    return START_STICKY; 
} 

private void cleanupAndStopServiceRightAway() { 
     // Add your code here to cleanup the service 

     // Add your code to perform any recovery required 
     // for recovering from your previous crash 

     // Request to stop the service right away at the end 
     stopSelf(); 
} 

另一種選擇是要求你的服務被停止(使用stopSelf())爲onTaskRemoved(),使Android的甚至沒有殺擺在首位的服務的一部分。

+0

你能保存一些東西到數據庫嗎? – 2017-01-20 06:57:00

相關問題