There is a service that listens for some voice. If voice matches a string a certain method is invoked in the service object.
public class SpeechActivationService extends Service {
public static Intent makeStartServiceIntent(Context pContext){
return new Intent(pContext, SpeechActivationService.class);
}
//...
public void onMatch(){
Log.d(TAG, "voice matches word");
}
//...
}
This is how I start the service in my activity:
Intent i = SpeechActivationService.makeStartServiceIntent(this);
startService(i);
From this service method, how can I invoke a method that resides in the activity object? I don't want access from activity to service, but from service to activity. I already read about handlers and broadcasters but could not find/understand any example. Any ideas?
After some research I found the following timings in my case for sending and receiving the broadcast. I have service in the same process.
sendBroadcast (Not recommended if both components are in same process) 34 sec
LocalBroadcastManager.getInstance(this).sendBroadcast(intent); close to 30 sec
Implementing using AIDL and RemoteCallbackList Will work for same process or different process
In your service
When you need call methods in Application/Acitvity from service
In your class extending Application or Activity.
Calling this way is almost instantaneous from broadcasting and receiving from the same process
I would register a BroadcastReceiver in the Activity and send an Intent to it from the service. See this tutorial: http://www.vogella.com/articles/AndroidBroadcastReceiver/article.html It might look a bit long but you'll want to learn how to use those anyway ;)
Assuming your Service and Activity are in the same package (i.e. the same app), you can use LocalBroadcastManager as follows:
In your Service:
In your Activity:
From section 7.3 of @Ascorbin's link: http://www.vogella.com/tutorials/AndroidBroadcastReceiver/article.html#ownreceiver_localbroadcastmanager
There are many different ways to achive this. One of them to use
Handler
andMessanger
classes. The idea of the method is to passHandler
object fromActivity
toService
. Every timeService
wants to call some method of theActivity
it just sends aMessage
andActivity
handles it somehow.Activity:
Service: