Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onStart() and onStartCommand() still called in 2.0 and higher

According to this blog post and the documentation of onStartCommand() if you have a Service you should implement onStart() and onStartCommand() and in 2.0 and higher only onStartCommand() will be called. It seems that this is not the case and in my Service BOTH are being called. This was a problem as it was trying to do the work twice, so I had to add a check in onStart() to not do anything if the OS version was < 2.0. This seems like a hack and a bug. Anyone else experience this or do I maybe have something wrong? I cut and pasted the code right from the sample.

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
  Util.log(mCtx, "AlerterService", "onStartCommand() called");
  handleStart(intent);
  return super.onStartCommand(intent, flags, startId);
}

public void onStart(Intent intent, int startId) {
    Util.log(mCtx, "AlerterService", "onStart() called");       
    handleStart(intent);
    super.onStart(intent, startId);
}
like image 951
sroorda Avatar asked Sep 21 '11 00:09

sroorda


People also ask

What should onStartCommand () return incase if the service gets killed by OS?

onStartCommand() The method also returns an int that can be one of the following three (I'm not including the compatibility constants): START_NOT_STICKY, START_STICKY and START_REDELIVER_INTENT. Which of these you return determines if and how your Service will be restarted if you app gets killed by the system.

What are the return value of onStartCommand () in Android services?

onStartCommand() is equivalent to returning START_STICKY . If you don't want the default behavior you can return another constant.

What is sticky and non sticky in Android?

START_STICKY. the system will try to re-create your service after it is killed. START_NOT_STICKY. the system will not try to re-create your service after it is killed. Standard example: @Override public int onStartCommand(Intent intent, int flags, int startId) { return START_STICKY; }


1 Answers

The source code of onStartCommand() is:

    public int onStartCommand(Intent intent, int flags, int startId) {
        onStart(intent, startId);
        return mStartCompatibility ? START_STICKY_COMPATIBILITY : START_STICKY;
    }

So it still calls onStart();

like image 130
songzhw Avatar answered Nov 03 '22 00:11

songzhw