2013-08-12 74 views
0

我創建了一個自定義的後臺服務,誰在擴展IntentService。當我的應用程序通過.startService()轉到後臺時,我正在調用這個類。在我返回START_STICKY的時候調用了第一個onStartCommand(就像我讀過其他一些文章,以保持我的服務活着並在由於內存不足而死的情況下在需要時重新創建)。之後,我實現了onHandleIntent(intent)方法,我從調用者的意圖中獲取額外的內容,在這裏我開始一個Timer來運行每分鐘,並執行簡單的代碼。但問題在於,當應用程序處於後臺時,30分鐘後我的服務被殺死,不會重新創建。這是我的代碼的一部分,所以任何建議都是完美的。IntentService在30分鐘後死亡,當我的應用程序在後臺時

@Override 
public int onStartCommand(Intent intent, int flags, int startId) { 
    super.onStartCommand(intent, flags, startId); 
    return START_STICKY; 
} 

@Override 
protected void onHandleIntent(Intent workIntent) { 
    //here I'm initializing the Timer 
} 

class UpdateTimeTask2 extends TimerTask { 
    public void run() { 
     backgroundTimer();//here I'm doing some simple coding 
    } 
} 
+0

IntentService不是爲了..使用服務,而不是 –

+0

好吧,我現在會嘗試。 – Slavcho

回答

2

因此,正如Kumar所說,我應該擴展Service not IntentService。調用服務與調用IntentService相同,唯一的區別是Service類需要未實現的方法。此外,我使用Handler的postDelayed方法代替Timer,並且在onStartComand中我還返回了START_STICKY。所以這項服務根本不會被殺死。有用的代碼可以在herehere找到。我希望這有幫助。

1

在這種情況下,正常的服務和處理程序應該是你所需要的。正如Pankaj所寫,IntentServices不是長期運營的設計者。然後,您可以使用Handler的postDelayed方法每分鐘執行一次您的代碼。

相關問題