I'm writing an music player app. I have the MediaPlayer object in a service. The problem is
that I don't know how to update the UI from service. By example I want to update the remaining time from current song but - because the MediaPlayer is on service - I can't set a listener to MediaPlayer object.
I was thinking about sending a broadcast message with current time but if I'll do it in this way, I have to send a message on every second. I suppose this will affect the speed of application + battery life.
Another solution can be to create a public static
variable in Service and access it from activity but I read that this is not a good option.
What do you think? Do you know any - better - way to update the UI from service?
Thank you.
I haven’t worked with the media player, but I assume that you want to start the service from your activity (using startService) to start playing music, and then you want to bind to the service (using bindService) to be able to register listeners that will deliver information back from the service (the service will wrap the callbacks from the media player) to the activity and offer the possibility to change track etc. while the activity is visible.
So, you need to implement your service as both a started service (to be able to play music while you application is in the background) and a service that it is possible to bind to (to be able to control it when your application is in the foreground). Assuming that you service is running in the same process as your client activity it is very simple to implement this. And, I would also recommend you service to be running in the foreground to avoid it being killed by the system.
Started service: http://developer.android.com/guide/topics/fundamentals/services.html#ExtendingIntentService
Local service that your client activity should bind to when it is displayed: http://developer.android.com/guide/topics/fundamentals/bound-services.html#Binder
You can do this by binding your service to activity .Perform this using AIDL in android.
Here is a very good example of AIDL
What you actually need to do is create your MediaPlayer in your SERVICE, create a class that extends ServiceConnection and in your .aidl file make some interface methods like this :
interface IPlayerService {
// You can pass values in, out, or inout.
// Primitive datatypes (such as int, boolean, etc.) can only be passed in.
void play();
void pause();
void stop();
boolean isPlaying();
int maxDuration();
int getCurrentPosition();
void changePosition(int a);
void seekComplete();
boolean isMusicCompleted();
}
Define these methods in your service class by creating a new stub in onBind(Intent intent) method of the service class.
Now from your mainActvity interact with service to update your UI .
How to perform these things is given by an example in the above link of AIDL & bind music app to service.
Hope this will help you to solve your issue.