I’ve created a simple Android application for testing how to use a handler or handlers to pass data from a background Service/thread to some other activity other than the MainActivity that created the background service. I’ve got the Service, thread, and a handler working in the MainActivity. The last step is to get a handler to pass data to some other activity other than the MainActivity. I can get the Service to pass messages to the MainActivity’s handler, but I don’t know how to get it to pass data to some other activity.
Why would anyone want to do this? I thought this compared to a simple MP3 player, but what it actually compares to is a nice FM radio. The MainActivity uses a background Service that allows me to select an FM station. When I launch the Play activity it should bind to the same background Service so I can continue to listen while it (the nice part) displays a graphic equalizer or animation of the the audio. Basically, I don’t know how to bind to the background Service from more than one activity.
Please have a look at my current code. It consists of three carefully commented files that describe what I am trying to do and the difficulties I am having passing data to some other activity in addition to the MainActivity:
Any help using a background Service, thread, and handler(s) to pass data to some other activity in addition to the MainActivity that created the backgraound Service would be greatly appreciated.
Handler is associated with specific thread, so for as long as you create it in UI thread all you need to do is to share the handler. I would put your handler in my
Application class. And you can put the whole
Messenger there, if you want. Then you can access handler in any activity via
((MyApplication)getApplication()).getHandler(). When activity starts or pauses, you can register it as a callback.
So something like this
In any activity that needs to do receive requests via messenger
This is just an idea. You may need to tune it to your needs.
And don’t forget to set
MyApplication name in AndroidManifest.xml