starting android service using explicit vs implicit intent

后端 未结 2 2117
别那么骄傲
别那么骄傲 2021-02-14 09:41

According to the standard Android documentation, the prefered way to start a service (started service that is) is to use an explicit intent like this:

// Using e         


        
相关标签:
2条回答
  • 2021-02-14 10:25

    A1 : Even though your activity and service run in different processes they still belong to same Application. You can still use explicit intent, I don't see any specific advantage of using implicit intent here (let me know if find any :) )

    A2 : let me list down few facts here

    • Life cycle of "Started" service (rather than "Bind"ed service) is independent of the life cycle of Activity which has started this service. This is true irrespective whether both are running in the same process or not.
    • Only one instance of Service will be alive at any point of time. when your activity calls startService() , service instance will be created if it is not already running (in this case you service will receive onCreate() callback as well). But if Service is already running, Framework would simply call onStartCommand() callback on already running process(No onCreate() callback in this case). Again all this is true irrespective of activity and service are running on same process or different processes.

    Now to answer your question, if you service is still running (because of startService() call by previous activity), then bindService()/startService() will make sure to connect to existing service.

    Hope this is of some help to you. Let me know if you have any other specific questions.

    0 讨论(0)
  • 2021-02-14 10:31

    You don't need to use an implicit intent to start a service or activity in a separate process; however, using a separate process for an Activity is a rare scenario. Using a separate process for a Service is more common, but nevertheless I'd like to know what the use case is.

    If your application process is destroyed and then restarted, you'd use startService to reconnect to the Service. If the Service is running, you connect to it, otherwise the Service is restarted. If you then want to kill the Service, you can kill it, or you can run stopService() from your main app.

    What is the service doing?

    0 讨论(0)
提交回复
热议问题