项目要求
- 使用broadcast和service实现音乐播放、暂停、切换
- 播放时能显示歌曲名与歌手名
演示效果
项目结构
实现思路
- MainActivity启动服务,将播放、暂停、停止、切换信号发送广播给Service
- MusicService 调用函数Prepareandplay()播放音乐,发送广播给MainActivity返回歌曲id
- PrepareAndPlay() 定向操作 打开并播放音乐文件
记录
- assets相比res管理更松散,可以定义下级子文件夹,且assets中的资源不占用APK空间
- 原来是BroadcastReceiver,现在在Activity里,创建一个ActivityReceiver子类来代替其功能
- BroadcastReceiver可以接收来自系统和应用的的广播,但来自系统的广播不用我们人为发送
主要代码
MainActivity.java
public class MainActivity extends Activity implements View.OnClickListener {
TextView title, author;
ImageButton play, stop,last,next;
ActivityReceiver activityReceiver;
public static final String CTL_ACTION=
"org.crazyit.action.CTL_ACTION";
public static final String UPDATE_ACTION=
"org.crazyit.action.UPDATE_ACTION";
int status = 0x11;
String[] titleStrs = new String[] {
"Take Me Home Country Roads","好想爱这个世界啊","You Are Not Alone","七里香"};
String[] authorStrs = new String[] {
"John Denver","华晨宇","Michael Jackson","周杰伦"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
activityReceiver = new ActivityReceiver();
IntentFilter filter = new IntentFilter();
//指定BroadCastReceiver监听的action
filter.addAction(UPDATE_ACTION);
registerReceiver(activityReceiver,filter);
Intent intent = new Intent(this,MusicService.class);
startService(intent);
//找到对应控件
play = this.findViewById(R.id.imgplay);
stop = this.findViewById(R.id.imgstop);
next = this.findViewById(R.id.imgnext);
last = this.findViewById(R.id.imglast);
title = this.findViewById(R.id.txttitle);
author = this.findViewById(R.id.txtauthor);
//添加监听
play.setOnClickListener(this);
st