Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android service onStartCommand never called

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;
}
like image 645
Asaf Pinhassi Avatar asked Oct 17 '12 06:10

Asaf Pinhassi


1 Answers

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.

like image 70
kpninja12 Avatar answered Sep 25 '22 22:09

kpninja12