Android application as a service without activity

梦想的初衷 提交于 2019-12-11 18:17:14

问题


I am making a set of apps and I have pretty much the same background service for all of them.

I'm trying to make an app that has only this Service. so I don't repeat it in all of them, but the thing is don't need any Activity. because there is no UI needed for it, and so the user can't close it except if they stop the Service.

I tried to remove the Activity, but then the app doesn't run or start. My question is: can I make an app exactly like Google Play Services so other apps can use its Service.

If yes than a snippet or a sample would be very welcome.


回答1:


Sure! No reason you cannot have an application with only a service. ...and no need to get into AIDL unless you want to.

The problem is, how to make the application run. When you create an application with an Activity, you add an Intent filter, in the manifest, that makes the activity startable from the Launcher. If there's no activity, you'll have to find another way to start it.

It is easy to do, though. Just fire an intent from one of your other programs, like this:

startService(new Intent("my.service.intent"));

... where the service is registered your manifest, like this:

        <service android:name=".SomeService" >
          <intent-filter>
            <action android:name="my.service.intent"/>
          </intent-filter>

You could use that intent to pass Parcelable parameters to the service, and the service can reply by broadcasting intents back.

Of course startService and broadcastIntent are a bit clunky if you really need a complex API between applications and your service. If you need something richer, you will want to look into AIDL and a Bound Service.

Edited to add Intent Filter




回答2:


Yes, I think you're looking for AIDL. Have a look at this thread?

https://groups.google.com/forum/#!topic/android-developers/LuWPZjPZ0sk



来源:https://stackoverflow.com/questions/49574844/will-service-be-called-if-application-has-no-activity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!