首先贴个地址
https://github.com/greenrobot/EventBus
Android EventBus
是基于事件驱动的一个开源库,也算是一个观察者模式Observe,扩展性强使用简单,用发布者和订阅者很好的解决了两个模块之间的通信,如Fragment和Activity,Activity和Service之间的通信啊,支持自定义消息类型来传输,最近公司的一个项目控制音乐的播放,我也用到了EventBus,由Activity向Service发送消息,Service来控制音乐曲目的播放,代码片段
Service
public void onEventBackgroundThread(MyEvent event){
Log.e("TAGEVENT",event.getPath());
if (event.getPath()=="null")
{
if (mPlayer.isPlaying()==false)
{
int r=new Random().nextInt(8);
Log.e("TAGRANDOM",""+r);
mPlayer.reset();//idle
try
{
mPlayer.setDataSource("/storage/emulated/legacy/res/common/sound/"+musicesource[r]+".mp3");
mPlayer.prepare();
mPlayer.start();
}
catch (IllegalArgumentException e)
{
e.printStackTrace();
}
catch (SecurityException e)
{
e.printStackTrace();
}
catch (IllegalStateException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
else
{
Log.e("TAGP","We are Playing ,baby");
}
}
else
{
Log.d("harvic", "onEventBackground收到了消息:" + event.getPath());
mPlayer.reset();//idle
try
{
mPlayer.setDataSource(event.getPath());
mPlayer.prepare();
mPlayer.start();
}
catch (IllegalArgumentException e)
{
e.printStackTrace();
}
catch (SecurityException e)
{
e.printStackTrace();
}
catch (IllegalStateException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
public void play()
{
mPlayer.reset();//idle
try
{
mPlayer.setDataSource(path);
mPlayer.prepare();
mPlayer.start();
}
catch (IllegalArgumentException e)
{
e.printStackTrace();
}
catch (SecurityException e)
{
e.printStackTrace();
}
catch (IllegalStateException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
class MediaBinder extends Binder
{
public void play()
{
MediaService.this.play();
}
}
@Override
public IBinder onBind(Intent intent)
{
return new MediaBinder();
}
}
Activity
//背景音乐设置————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————if (mScenes.get(position).getBackground_music() == "null") {
Log.e("error", "/storage/emulated/legacy/res/common/sound/" + mScenes.get(position).getBackground_music());
EventBus.getDefault().post(new MyEvent("null"));
} else {
EventBus.getDefault().post(new MyEvent("/storage/emulated/legacy/res/common/sound/" + mScenes.get(position).getBackground_music()));
Log.e("bmg", "/storage/emulated/legacy/res/common/sound/" + mScenes.get(position).getBackground_music());
}