简体   繁体   中英

Event Raise on Service

Think I have a service that play musics , Also I have an actvity that bind to this service , I want when this service started a new music , raise an event and Activity shows a toast , how can I do this , like here

Service service = new se...
BindToService();

service.OnMediaPlayerStarted(new Event(

public void run()
{

};
));

I want to craete a custom event like MediaPlayerStarted and when

You can do this in Two ways:

1) Use a LocalBroadcastManager and write a receiver for sending and receiving the Broadcasts within the application (Might be heavy and complex, so not expanding the details, but works).

2) Use Message passing using Handler (This is Simple).

  • Create a Handler in Main Activity and pass its reference to Service
  • Send a Empty Message using the Activity handler with respective event ID and update the UI accordingly in the Activity.
  • Refer to this Example. - This user TimerTask and Runnables but for your pupose just send empty Message using the Handler and handle them in handleMessage(Message msg) call back of Handler.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM