上一篇博客说道除了可以使用bindService()开启Service从而实现在Activity与Service通信之外,还有一个方法,那就是:使用广播BroadCast Receiver
现在做一个简单地音乐播放器,讲解这个原理。
在此之前,我们需要了解如何使用BroadCast:
1.在Activity或者Service中定义一个Intent,并且指定Action属性;
2.再定义一个IntentIntentFilter,用来注册BroadCast Receiver,或者是在AndriodMainifest.xml中注册;
3.调sendBroadCast()方法发送这个注册过的与Intent对应的广播。(广播中重写onReceive()方法)。
接下来就可以做这个播放器了,布局界面非常简单,在此不赘述。
ps:在assets文件中要添加三首歌哦
首先写主Activity,在此中,我们定义了一个继承了BroadCast的内部类,并且在activity中注册了这个BroadCast Receiver,也就是说,该BroadCast Receiver监听这与intentfilter相对应的Intent-----当一首歌结束了或者播放状态改变,都会引起发送广播给Activity;
同理,在Service中我们定义了另一个广播,显然它是监听与其Intentfilter对应的Intent-------当在应用界面切换歌曲时引发发送广播给Service;
这样,Activity与Service之间就形成了通信,并且是相互的。
public class MusicBox extends Activity
implements OnClickListener
{
// 获取界面中显示歌曲标题、作者文本框
TextView title , author;
//播放/暂停、停止按钮
ImageButton play , stop;
ActivityReceiver activityReceiver;
public static final String CTL_ACTION
= "org.crazyit.action.CTL_ACTION";
public static final String UPDATE_ACTION
= "org.crazyit.action.UPDATE_ACTION";
// 定义音乐的播放状态,0x11代表没有播放;0x12代表正在播放;0x13代表暂停
int status = 0x11;
String[] titleStrs = new String[]{
"心愿",
"约定",
"美丽新世界"
};
String[] authorStrs = new String[]{
"未知艺术家",
"周蕙",
"伍佰"
};
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// 获取程序界面界面中的两个按钮
play = (ImageButton) this.findViewById(R.id.play);
stop = (ImageButton) this.findViewById(R.id.stop);
title = (TextView) findViewById(R.id.title);
author = (TextView) findViewById(R.id.author);
// 为两个按钮的单击事件添加监听器
play.setOnClickListener(this);
stop.setOnClickListener(this);
activityReceiver = new ActivityReceiver();
//
IntentFilter filter = new IntentFilter();
filter.addAction(UPDATE_ACTION);
registerReceiver(activityReceiver, filter);
//注册BroadCast,监听歌曲完成时间(在MUsicService里面)
Intent intent = new Intent(this, MusicService.class);
// 启动后台Service
startService(intent);
}
// 自定义的BroadcastReceiver,负责监听从Service传回来的广播
public class ActivityReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
// 获取Intent中的update消息,update代表播放状态
int update = intent.getIntExtra("update", -1);
// 获取Intent中的current消息,current代表当前正在播放的歌曲
int current = intent.getIntExtra("current", -1);
if(current >= 0)
{
title.setText(titleStrs[current]);
author.setText(authorStrs[current]);
}
switch (update)
{
case 0x11:
play.setImageResource(R.drawable.play);
status = 0x11;
break;
// 控制系统进入播放状态
case 0x12:
// 播放状态下设置使用暂停图标
play.setImageResource(R.drawable.pause);
// 设置当前状态
status = 0x12;
break;
// 控制系统进入暂停状态
case 0x13:
// 暂停状态下设置使用播放图标
play.setImageResource(R.drawable.play);
// 设置当前状态
status = 0x13;
break;
}
}
}
@Override
public void onClick(View source)
{
// 创建Intent
Intent intent = new Intent("org.crazyit.action.CTL_ACTION");
switch (source.getId())
{
// 按下播放/暂停按钮
case R.id.play:
intent.putExtra("control", 1);
break;
// 按下停止按钮
case R.id.stop:
intent.putExtra("control", 2);
break;
}
// 发送广播 ,将被Service组件中的BroadcastReceiver接收到
sendBroadcast(intent);
}
}
再写Service:
public class MusicService extends Service
{
MyReceiver serviceReceiver;
AssetManager am;
String[] musics = new String[]{
"wish.mp3",
"promise.mp3",
"beautiful.mp3"
};
MediaPlayer mPlayer;
//当前的状态,0x11 代表没有播放 ;0x12代表 正在播放;0x13代表暂停
int status = 0x11;
// 记录当前正在播放的音乐
int current = 0;
@Override
public IBinder onBind(Intent intent)
{
return null;
}
@Override
public void onCreate()
{
am = getAssets();
// 创建BroadcastReceiver
serviceReceiver = new MyReceiver();
//
IntentFilter filter = new IntentFilter();
filter.addAction(MusicBox.CTL_ACTION);
registerReceiver(serviceReceiver, filter);
//注册Myservice,监听MusicBOx里面切换播放状态
// 创建MediaPlayer
mPlayer = new MediaPlayer();
// 为MediaPlayer播放完成事件绑定监听器
mPlayer.setOnCompletionListener(new OnCompletionListener()
{
@Override
public void onCompletion(MediaPlayer mp)
{
current++;
if (current >= 3)
{
current = 0;
}
/* 发送广播通知Activity更改文本框 */
Intent sendIntent = new Intent(MusicBox.UPDATE_ACTION);
sendIntent.putExtra("current", current);
// 发送广播 ,将被Activity组件中的BroadcastReceiver接收到
sendBroadcast(sendIntent);
// 准备、并播放音乐
prepareAndPlay(musics[current]);
}
});
super.onCreate();
}
public class MyReceiver extends BroadcastReceiver
{
@Override
public void onReceive(final Context context, Intent intent)
{
int control = intent.getIntExtra("control", -1);
switch (control)
{
// 播放或暂停
case 1:
// 原来处于没有播放状态
if (status == 0x11)
{
// 准备、并播放音乐
prepareAndPlay(musics[current]);
status = 0x12;
}
// 原来处于播放状态
else if (status == 0x12)
{
// 暂停
mPlayer.pause();
// 改变为暂停状态
status = 0x13;
}
// 原来处于暂停状态
else if (status == 0x13)
{
// 播放
mPlayer.start();
// 改变状态
status = 0x12;
}
break;
// 停止声音
case 2:
// 如果原来正在播放或暂停
if (status == 0x12 || status == 0x13)
{
// 停止播放
mPlayer.stop();
status = 0x11;
}
}
/* 发送广播通知Activity更改图标、文本框 */
Intent sendIntent = new Intent(MusicBox.UPDATE_ACTION);
sendIntent.putExtra("update", status);
sendIntent.putExtra("current", current);
// 发送广播 ,将被Activity组件中的BroadcastReceiver接收到
sendBroadcast(sendIntent);
}
}
//播放功能
private void prepareAndPlay(String music)
{
try
{
// 打开指定音乐文件
AssetFileDescriptor afd = am.openFd(music);
mPlayer.reset();
//使用MediaPlayer加载指定的声音文件。
mPlayer.setDataSource(afd.getFileDescriptor()
, afd.getStartOffset()
, afd.getLength());
// 准备声音
mPlayer.prepare();
// 播放
mPlayer.start();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
运行:
在点击播放按钮之后,将会播放第一首歌曲,并且循环播放(大笑可惜这里听不见声音),邮箱读者已经知道如何做到循环播放,但是如何做到设置播放模式,其实也很简单,我们只要在MusicService中setContentLisetner中多设置几行代码,再在Activity中加一些组件,在此不做赘述。
另外,由于播放功能是由Service控制的,当按返回退出时,音乐播放的进程并没有停止。