Search code examples
androidmultithreadinghandlerandroid-handler

Mechanism for passing data from one callback to another


I want to use Speech to text in my app for actions such as click of a yes or no button. I implemented the speech to text in my app.

In that I have a callback method called

   public void onResults(Bundle bundle) {

   //here I am getting Yes or No commands via User's Speech
   //bundle object has the data yes/no

   }

I want to use the result above as an input for some other task which are running in different threads, like for playing or pausing music and turning flash light on or off.

For doing this consider I have these methods below

music.play()
music.pause()
flashlight.on()
flashlight.off()

My question is how can I create such a mechanism so that I use Speech to text callback result data and pass it to different task's running in an separate threads and call music.play() or flashlight.on()

I tried to use Handlers for this with sendmessage() and handlemessage() methods. But I am not able to figure out how can I implement it when main thread is not involved. Because my other task's are there in separate threads.

Can anyone help me with a prototype for this or just the data flow process will be really helpful.


Solution

  • Bus-Message (event oriented) way can fit for your problem. F.e. we have SomeEventHappenedMessage class with some data inside. When some event is happens, message is sent through the bus and listeners will obtain it.

    You can write your own bus or use EventBus library https://github.com/greenrobot/EventBus for sending and obtaining messages/events.

    Pseudocode:

    //listener registers/unregisters when needed
    Bus.register()
    Bus.unregister()
    
    //listener listens for message
    onMessage(SomeEventHappenedMessage msg) {
        if msg.hasSomeData {
             music.play()
        } else {
             music.stop()
        }
    }
    
    //message being sent
    SomeEventHappenedMessage message = (message creation)
    Bus.sendMessage(message)