I have seen many posts in SO regarding this but could not get the exact and most easy way to call an activity method from service class. Is broadcast receiver only the option? No easy way out ? I just need to call the following method in Activity class after the media player is prepared in Service class .
Activity class:
public void updateProgress() {
// set Progress bar values
songProgressBar.setProgress(0);
songProgressBar.setMax(100);
// Updating progress bar
updateProgressBar();
}
Service class:
@Override
public IBinder onBind(Intent intent) {
Log.d(this.getClass().getName(), "BIND");
return musicBind;
}
@Override
public boolean onUnbind(Intent intent) {
return false;
}
@Override
public void onPrepared(MediaPlayer mp) {
try {
mp.start();
} catch (IllegalStateException e) {
e.printStackTrace();
}
// updateProgress();// Need to call the Activity method here
}
You can't call your sevices method direcly from your activity or vise versa. There are 3 ways to communicate with a service; using broadcasters and receivers, using
Messenger
or binding to the service. For further information look at http://developer.android.com/guide/components/bound-services.htmlI created a general class called Delegate (it's not a special name, you can name it John) and passed MainActivity class into it as a static field. Then I can access it from the service since its global now. I am not sure if it is cost-effective but it solved the problem for me simple.
My service:
Delegate class:
What I did in MainActivity:
Define an interface your Service will use to communicate events:
Write your Service class. Your Activity will bind to this service, so follow the sample shown here. In addition, we will add a method to set the
ServiceCallbacks
.Write your Activity class following the same guide, but also make it implement your ServiceCallbacks interface. When you bind/unbind from the Service, you will register/unregister it by calling
setCallbacks
on the Service.Now when your service wants to communicate back to the activity, just call one of the interface methods from earlier. Inside your service:
Use Broadcast receiver with service for updating your view from the service class. For example:
In my activity class
And in my service class I am calling my update ui after a few interval of time which updates my UI.
For complete code check this link
You can call a method of activity from service by implementing your own listener like this https://stackoverflow.com/a/18585247/5361964
You might consider running your activity method in
runOnUiThread
like this:You can call from your service
and in your activity you set up a
the onChange method will ba called on the UI thread