Reputation: 12808
I'm still fresh to Android and Id think the below config works for launching my service when the app launches.
<service android:name=".PlaylistUpdaterService">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</service>
But this is not the case. What did I miss?
Upvotes: 15
Views: 29894
Reputation: 1710
Wrong! extend the Application
class (IE make your own), then in the onCreate()
method do this.
//Service is below
Intent serviceIntent = new Intent(getApplicationContext(), PlaylistUpdaterService.class);
startService(serviceIntent);
And take that intent filter crap out of your declaration in the manifest file. Leave it as
<service android:name=".PlaylistUpdaterService">
The intent filter following needs to be in your home activity only
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
The reason you do this is because the Application
class is started up as soon as the app is, and acts as kind of a global class the the android framework manages.
Actually if you want the service to run every time you go back to your home screen, you should start the service in your home classes onResume()
. Putting it in the applications onCreate()
will only start the service if the user is launching for the first time, or after the running process has been killed. Or you could put it in your home classes onCreate()
but that is not even guaranteed to run every time.
Upvotes: 25
Reputation: 11028
Correct me if I am wrong, but android.intent.category.LAUNCHER is valid only for Activity. So, does not look like valid way to start Service. The same you can achieve if you do the following:
@android:style/Theme.NoDisplay
under Theme tag for this Activity in AndroidManifest.xml.
onCreate()
of your Activity. finish()
in onStart()
of your Activity to close it.So, your Activity will be invisible to the user, last shortly and nobody will notice that it was used to start the service.
Upvotes: 9