Can I start a service without activity or receiver

2019-01-25 11:14发布

问题:

I want to start a service in an APK.

I tried to use as following:

<application android:icon="@drawable/icon" android:label="@string/app_name">  
        <service android:name =".TestServcie">  
            <intent-filter>  
                <action android:name="android.intent.action.MAIN" />  
                <category android:name="android.intent.category.LAUNCHER" />  
            </intent-filter>  
        </service>  
    </application>

Any ideas?
Thanks

回答1:

No you can't.

Create a simple Activity which starts the service and simply provides some feedback to the user (to tell them the service has started for example) and set that Activity with the MAIN/LAUNCHER intent.



回答2:

You can write a BroadcastReceiver and run the Service after receiving the Intent. For example after device boot-up or other Intent that you need.

<receiver android:name=".StartupReceiver">
   <intent-filter>
     <action android:name="android.intent.action.BOOT_COMPLETED"/>
     <category android:name="android.intent.category.HOME"/>
   </intent-filter>
</receiver>