Dan Wuensch
Dan Wuensch

Reputation: 132

How do you detect from a service that the app process has closed?

I have an Android app that consists of a Service and various activities. When the app starts, the Service is started with startService(Intent service). Various activities (but not all activities) bind to the Service and send/receive messages from it. The service should be alive while the app is in the foreground on any activity or in the background, but should end when the entire app is closed (i.e. user swipes the app from Recent Apps screen).

How do I determine from the Service (which currently never stops running until you manually stop it on the device) that the app process has ended so that I can then stop the service?

Upvotes: 1

Views: 329

Answers (2)

CommonsWare
CommonsWare

Reputation: 1007296

Since the service is hopefully part of the same process as everything else, it will not be notified that the process has terminated, because the process will be terminated, and so the service's code will no longer be running. There is no advance warning of a process being terminated.

If for some reason you put the service in a separate process, please reconsider that.

Also, note that IntentService is not really designed for use with the binding pattern. An IntentService is designed for transactional work, performed on a background thread. The use of IntentService for anything else is a major code smell.

Upvotes: 2

Artyomcool
Artyomcool

Reputation: 381

Just don't start service manually. When you bind it from activities it starts and shuts down automatically.

Upvotes: 0

Related Questions