Android Studio简易音乐播放器设计作业
利用BroadcastReceiver模拟音乐播放器,实现播放、暂停、音乐切换、显示当前歌曲信息等基本功能。
实验成功展示
实验代码
MainActivity.java
activityReceiver用于监听Service传回的广播,onCreate()函数
用于获取相应按钮以及添加监听器、注册receiver,ActivityReceiver子类,负责监听从Service传回来的广播,并用switch控制系统状态,且定义了在音乐播放的不同状态下显示的图片,onClick函数,用switch判断点击事件,向Service发送广播
//
package com.example.mymusicbox;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
public class MainActivity extends Activity implements View.OnClickListener
{
// 获取界面中显示歌曲标题、作者文本框
TextView title, author;
// 播放/暂停、停止按钮
ImageButton play, stop,front,next;
ActivityReceiver activityReceiver;
public static final String CTL_ACTION = "org.xr.action.CTL_ACTION";
public static final String UPDATE_ACTION = "org.xr.action.UPDATE_ACTION";
// 定义音乐的播放状态,0x11代表没有播放;0x12代表正在播放;0x13代表暂停
int status = 0x11;
String[] titleStrs = new String[] {"雨爱","Legends Never Die","约定","心愿" };
String[] authorStrs = new String[] {"刘至佳", "英雄联盟","周蕙","4个女生" };
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 获取程序界面界面中的两个按钮
front=(ImageButton)this.findViewById(R.id.front);
play = (ImageButton) this.findViewById(R.id.play);
stop = (ImageButton) this.findViewById(R.id.stop);
next=(ImageButton)this.findViewById(R.id.next);
title = (TextView) findViewById(R.id.title);
author = (TextView) findViewById(R.id.author);
// 为两个按钮的单击事件添加监听器
play.setOnClickListener(this);
stop.setOnClickListener(this);
front.setOnClickListener(this);
next.setOnClickListener(this);
activityReceiver = new ActivityReceiver();
// 创建IntentFilter
IntentFilter filter = new IntentFilter();
// 指定BroadcastReceiver监听的Action
filter.addAction(UPDATE_ACTION);
// 注册BroadcastReceiver
registerReceiver(activityReceiver, filter);
Intent intent = new Intent(this, MusicService.class);
// 启动后台Service
startService(intent);
}
// 自定义的BroadcastReceiver,负责监听从Service传回来的广播
public class ActivityReceiver extends BroadcastReceiver
{
@Override