Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Service never appears to start - onStartCommand() not called

I am trying to create a service that will handle file I/O in the background. Activities that update the data will bind to the service and call the service's methods to perform the I/O. I am using the Android documentation for guidance.

My service does not seem to want to start, however. In the onCreate() method of my Activity, I have:

Intent smsIntent = new Intent(this, SurveyManagerService.class);    
String surveyFilename = getIntent().getStringExtra("surveyFilename");   
System.out.println(startService(smsIntent)); //testing if it starts
SurveyManagerServiceConnection connection = new SurveyManagerServiceConnection();
sms = connection.getSurveyManagerService();

At line 3 LogCat outputs a ComponentInfo object, so it would appear that the service is created; however, sms is null. Furthermore, the SurveyManagerService onStartCommand() method never seems to be called:

@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
    System.out.println("starting service");
    Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();
    openSurveyFromIntent(intent);
    return START_REDELIVER_INTENT;
}

I never see any "starting service" output in LogCat, nor does the Toast appear.

My service is declared in my manifest as:

<service android:name=".SurveyManagerService" android:exported="false" android:enabled="true">
</service>

Am I missing something obvious? Let me know what other information I should provide to diagnose the problem.

like image 850
Spinner Avatar asked Oct 07 '11 16:10

Spinner


3 Answers

Maybe you've accidentally placed the service tag outside application tag? Then the service just fails silently. Although there should be a "Unable to start service Intent..." error in the log.

like image 176
ohra Avatar answered Oct 13 '22 03:10

ohra


Be sure to declare your service in AndroidManifest.xml

<application>
    ...
    <service android:name=".path.to.service.MyService"/>
</application>
like image 37
Defuera Avatar answered Oct 13 '22 03:10

Defuera


It seems the onCreate() method has to exit before the service can actually start. Once I removed the getSurveyManagerService() request, and once a bit of time had passed, I received the System.out messages indicating the service was starting.

Unfortunately that creates another problem: the Activity relies on the Service for its data, so I need to determine how to cause the Activity to wait for the service to start.

EDIT: My solution was to create a private subclass of my ServiceConnection in my Activity. I then overrode the onServiceConnected() method to provide the Activity with its data (populating a ListView, in this case).

like image 6
Spinner Avatar answered Oct 13 '22 03:10

Spinner