5

I noticed that Service.START_STICKY doesn't work and when I tokk a closer look, I saw the onCreate() is running but onStartCommand is not called.

Any ideas why?

    @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;
}
Asaf Pinhassi
  • 15,177
  • 12
  • 106
  • 130

2 Answers2

15

If you have the same situation I had, my Service starts up and runs just fine (onCreate() and onServiceConnected() are both invoked) but onStartCommand(Intent,int) was never called. I found it's because the system started my Service instead of me explicitly starting the Service in code. According to the docs:

[onStartCommand(Intent,int) is] called by the system every time a client explicitly starts the service by calling startService(Intent)

So I had to call startService(new Intent(context, MyService.class)) explicitly in code to get onStartCommand(Intent,int) to trigger. Note that doing this will not restart the Service created by the system and it won't create a new instance of that Service either.

kpninja12
  • 529
  • 6
  • 11
2

Try to insert the line android.os.Debug.waitForDebugger(); at the end of onCreate(). The debugger didn't reach onStartCommand()'s breakpoints for me until I did this.

Trinimon
  • 13,839
  • 9
  • 44
  • 60
  • 1
    Worked for me. But when I removed it from the onCreate method to confirm that this was infact the problem, the problem had disappeared. – Zeezer Oct 25 '13 at 11:54