I’ve been trying to figure this out for a while now and can’t figure out why this is happening. This seems like it would be simple, but I can’t get this to work out.
Here’s what I’d like to happen
When I start the application,
1. If the background Service (long running singleton service) isn’t running, start it before starting the activity.
2. Start the “homepage” activity
Updated 8/20
Here’s what is happening:
1. I start the application and the service isn’t running
2. I kick off the intent (via context.startService)
– the context.startService is called
3. The activity runs to completion
4. The onStartCommand is run
How can I get the onStartCommand to run before the activity starts running??
Any advice on this would relieve a lot of frustration. I’ve searched the forums prior to asking this but couldn’t find anything that matches my issues
Thanks a lot!
Update
Thanks for the quick responses.
I should have mentioned that I’m already running this from an extension of Application (starting the service in the onCreate method).
In my current implementation (below), here’s what happens in order as I step through the app. I thought this would cause the service to run before the activity but the activity runs and then the service runs. This is the main point of my confusion.
1. the application onCreate is called
2. the startService method is run
3. the starting activity runs
4. the service onCreate is called
– the service onStart is never called (I’ll try the onStartCommand instead as I’m not targeting older platforms – thanks for that suggestion Alexander)
public class MyApp extends Application {
@Override
public final void onCreate()
{
if(!MyService.isRunning()) // this is a static method with thread lock
{
Intent i = new Intent(context, MyService.class);
i.setAction(MyConstants.INTENT_START_SERVICE);
context.startService(i);
}
}
}
Thanks to Alexander O for his comment that pointed me in the right direction to getting the onStart command to run. I still can’t get the onStartCommand to run before the activity though. Any suggestions?
My issue was that I had both an onStartCommand and an onStart function in my service.
Apparently I didn’t understand the function of onStartCommand and thought that it was just supposed to define the service type (STICKY, NOT_STICKY).
Once I removed onStart and moved the onStart code into onStartCommand the application began working.
For those wondering, here’s basically what I had.