第一步:在MainActivity中获取XML中的组件并初始化界面点击事件,在MainActivity建一个ActivityReceiver继承BroadcastReceiver用以监听歌曲状态的变化从而更新UI,代码如下:
public class MainActivity extends Activity implements View.OnClickListener{ TextView title,author,situation; Button play,stop; // 播放控制开始结束控制ACTION public static final String CTL_ACTION = "com.example.service_musicplayer.ctl_action"; // 歌曲播放状态ACTION public static final String UPDATE_ACTION = "com.example.service_musicplayer.update_action"; ActivityReceiver activityReceiver; //定义播放状态 0x11代表没有播放 0x12 代表正在播放 0x13代表暂停 int status = 0x11; // 存放歌曲名 String titleStr[] = {"Music-1","Music-2","Music-3"}; // 存放歌手名 String authorStr[] = {"author-1","author-2","author-3"}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); play = (Button) findViewById(R.id.play); stop = (Button) findViewById(R.id.stop); title = (TextView) findViewById(R.id.title); author = (TextView) findViewById(R.id.author); situation = (TextView) findViewById(R.id.situation); play.setOnClickListener(this); stop.setOnClickListener(this); // 使用代码方式为broadcastReceiver注册监听 activityReceiver = new ActivityReceiver(); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(UPDATE_ACTION); // 注册broadcastReceiver registerReceiver(activityReceiver,intentFilter); Intent intent = new Intent(this,MusicService.class); startService(intent); } @Override public void onClick(View v) { Intent intent = new Intent(); intent.setAction(CTL