Reputation: 163
What difference does it create to listen to accelerometer in android application in an Activity vs in a Service other than that Activity runs in foreground and service runs in background.
QUES1: Will a listener get unregistered if it's registered in an activity and I don't unregister it explicitly rather close the activity (application).
QUES2: If the listener is registered in a Service, will it continue to listen to accelerometer even when application is closed if I don't explicitly unregister given that main thread of activity will die as soon as I close the activity and Service runs in same thread if not started in a new thread? I did read that background service will keep running and listen to sensors, but not able to understand how does it actually works.
What I wanted to achieve was:
On click on a button in Activity, my service starts listening to Accelerometer. even if the application is closed, it should keep listening
On click of a button in Activity, it should stop listening.
I have achieved the functionality of button click and listener on off BUT in Activity and now want to do the same in service and don't want listener to die when I close application.
Upvotes: 0
Views: 159
Reputation: 3334
Will a listener get unregistered if it's registered in an activity and I don't unregister it explicitly rather close the activity (application).
No, it won't. Most possibly, you will leak your listener, that would have otherwise been garbage-collected upon Activity destruction. That's bad practice. Always explicitly unregister things that you registered in your Activity. That's how it works.
..will it continue to listen to accelerometer even when application is closed if I don't explicitly unregister..
As long as a Service runs, it will continue to listen to accelerometer events, unless you explicitly unregister your listener. Be careful, that is exhaustive for the device battery. Especially, if your service is long-running and your sensor rate is high
and Service runs in same thread if not started in a new thread.. not able to understand how does it actually works.
By default, service runs on the same thread as the Activity, which started the service - so called UI thread. Closing the Activity will not eliminate this thread. The service will continue to receive the events it has subscribed to.
I have achieved the functionality of button click and listener on off BUT in Activity and now want to do the same in service and don't want listener to die when I close application.
As long as your Service lives, your listener will continue to live. Just explicitly unregister this listener, for example, in service's onDestroy()
. And keep in mind, that background services are good candidates to be killed unless they're explicitly started in foreground.
Upvotes: 1