Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regarding BroadCast Receiver and Service

Tags:

android

The application is being developed in 2.3.3

In my application, I am starting a service from a broadcast receiver. The service calls the Location Manager and gets latitude and longitude. Is it possible to send the latitude and longitude values back to broadcast receiver from Service?

If Yes? How do we do it?

If No? -> which is my approach as of now... I have used a SharedPreferences object to hold these values and access them in BroadCast Receiver. Will this work?

I do have few more questions on this, will edit my question after the answers... Thanks..

[Edit] Answer to my above question -> So we can send data from Service to Broadcast Receiver, though it's not a good practice in general.

like image 446
Vamsi Challa Avatar asked Feb 01 '26 09:02

Vamsi Challa


1 Answers

It is possible to pass the information back to the broadcast receiver by broadcasting a new intent from the service that has the location data. You will need to create a custom action for the intent and have your broadcast receiver register to handle that action. Creating and receiving intents with custom actions is described here.

However, I think in pretty much every case this is a bad approach. In general broadcast receivers should merely parse intents and launch intent services to do all of the work. If something needs to be done with the location then the service should do it not the broadcast receiver. It is also important to note that at the end of onReceive() the broadcast receiver is immediately destroyed so you lose all of its state.

I'd be happy to answer more questions or update my answer to be more specific if you provided more information as to the purpose of lat/long gathering task.

[EDIT] Since I can't comment I'll add my two cents to Kerim's answer. Unless I am missing something huge (if I am please let me know Kerim since you can comment on mine) may not work the way you expect. When the broadcast receiver's onReceive() function finishes the broadcast receiver will be destroyed. The handler you sent will live on but any data in the broadcast receiver will not exist and the handler will not be able to call the broadcast receiver's functions. Since the handler can't access any of the broadcast receiver's data or functions, you might as well do everything that needs to be done in the service.

like image 193
Sam Burba Avatar answered Feb 02 '26 22:02

Sam Burba