2012-10-17 107 views
5

我注意到Service.START_STICKY不起作用,當我仔細看看時,我看到onCreate()正在運行,但onStartCommand未被調用。Android服務onStartCommand從來沒有叫

任何想法爲什麼?

@Override 
public void onCreate() { 

    mGlobalData = GlobalData.getInstance(); 
    mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); 

    if (mTimer == null) 
     mTimer = new Timer(); 

    Log.e(TAG, "onCreate()"); 
} 

@Override 
public int onStartCommand(Intent intent, int flags, int startId) { 
    int t = START_STICKY; 
    Log.e(TAG, "call me redundant BABY! onStartCommand service"); 

    // We want this service to continue running until it is explicitly 
    // stopped, so return sticky. 
    return t; 
} 

回答

1

嘗試插入線android.os.Debug.waitForDebugger();onCreate()結束。調試器沒有達到onStartCommand()的斷點,直到我做到這一點。

+1

爲我工作。但是,當我從onCreate方法中刪除它以確認這實際上是問題時,問題就消失了。 – Zeezer

8

如果你有和我一樣的情況,我的Service啓動並且運行良好(onCreate()onServiceConnected()都被調用),但從未調用過onStartCommand(Intent,int)。我發現這是因爲系統啓動了我的Service,而不是我明確地在代碼中啓動Service。按照docs

[onStartCommand(Intent,int)被]叫做由每一個客戶明確地啓動該服務時,系統通過調用startService(Intent)

所以我不得不顯式調用startService(new Intent(context, MyService.class))的代碼來獲取onStartCommand(Intent,int)到觸發。請注意,這樣做不會重新啓動系統創建的服務,也不會創建該服務的新實例。