开发者

How to launch a Android Service when the app launches?

开发者 https://www.devze.com 2023-01-31 14:15 出处:网络
I\'m still fresh to Android and Id think the below config works for launching my service when the app launches.

I'm still fresh to Android and Id think the below config works for launching my service when the app launches.

    <service android:nam开发者_运维知识库e=".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?


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.


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:

  • create transparent Activity that will be used only to start Service
  • for that Activity, you do not need to specify GUI layout. So, you do not need to setContentView() in the activity's onCreate(). The only thing you need is to put

@android:style/Theme.NoDisplay

under Theme tag for this Activity in AndroidManifest.xml.

  • start Service from onCreate() of your Activity.
  • call 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消