Android学习之简易音乐盒设计

一、任务描述

利用BroadcastReceiver模拟音乐播放器。该播放器应具有最基本功能:播放、暂停、音乐切换、显示当前歌曲信息。

二、BroadcastReceiver简述

BroadcastReceiver是Android四大组件之一,是用来接收来自系统和应用中的广播。BroadcastReceiver有两种注册方式,分别是静态注册和动态注册。
静态注册
1.在AndroidManifest中的application标签下添加receiver子标签
2.通过name属性指定注册一个广播类,还有enabled与exported属性,enabled代表是否启用这个广播接收器,exported表示是否允许这个广播接收器接受本程序以外的广播
3.在receiver标签下添加intent-filter标签,设置对应action。action可以是系统定义的系统广播,也可以由开发者自己定义

//生成的receiver配置文件
19         <receiver
20             android:name=".MyReceiver"
21             android:enabled="true"
22             android:exported="true">
23             <intent-filter>
24             //自定义Action
25                 <action android:name="MLY" />
26             </intent-filter>
27         </receiver>

动态注册
1.在相关的activity中new MyBroadcastReceiver()

2.new intentFilter,调用其setAction()方法,参数中传入相关值的action调用3.context.registerReceiver()方法进行注册,方法的第一个参数为broadcastReceiver对象,第二个则是intentFilter对象

IntentFilter filter=new IntentFilter();
filter.addAction(MainActivity.CTL_ACTION);
registerReceiver(serviceReceiver,filter);

一般Android项目中是禁止使用静态注册的

三、任务过程

1.在AndroidManifest.xml里配置service

<service
    android:name=".MusicService"
    android:enabled="true"
    android:exported="true"></service>

2.一个assests文件用于存放.mp3文件,过程如下图:
在这里插入图片描述
前端设计

两个Textview控件以显示歌曲信息,四个ImageButton控件以实现相应功能
在这里插入图片描述
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="180dp"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/title"
        android:layout_width="match_parent"
        android:layout_height="32dp"
        android:layout_weight="1"
        android:gravity="center"
        android:text="歌曲"
        android:textSize="20dp"
        android:textColor="#9C27B0"
        android:ellipsize="marquee"
        android:marqueeRepeatLimit="marquee_forever"/> />

    <TextView
        android:id="@+id/author"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="演唱者"
        android:textSize="20dp" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="90dp"
        android:orientation="horizontal">

        <ImageButton
            android:id="@+id/front"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/front" />

        <ImageButton
            android:id="@+id/play"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/play" />

        <ImageButton
            android:id="@+id/stop"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/stop" />

        <ImageButton
            android:id="@+id/next"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/next" />

    </LinearLayout>

</LinearLayout>

功能实现
MainActivity.java
首先在函数最外层定义所需要用到的变量和子类。其中activityReceiver用于监听Service传回的广播

// 获取界面中显示歌曲标题、作者文本框
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个女生" };

onCreate()函数
用于获取相应按钮以及添加监听器、注册receiver

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);
}

ActivityReceiver子类,负责监听从Service传回来的广播,并用switch控制系统状态,且定义了在音乐播放的不同状态下显示的图片

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;
        }
    }
}

onClick函数,用switch判断点击事件,向Service发送广播

public void onClick(View source)
    {
        // 创建Intent
        Intent intent = new Intent("org.xr.action.CTL_ACTION");
        switch (source.getId())
        {
            // 按下播放/暂停按钮
            case R.id.play:
                intent.putExtra("control", 1);
                break;
            // 按下停止按钮
            case R.id.stop:
                intent.putExtra("control", 2);
                break;
            case R.id.front:
                intent.putExtra("control",3);
                break;
            //按下下一首
            case R.id.next:
                intent.putExtra("control",4);
                break;
        }
        // 发送广播,将被Service组件中的BroadcastReceiver接收到
        sendBroadcast(intent);
    }
}

MusicService.java
在最外层函数定义需要用到的变量和子类,String[]内容注意要和mainActivity中的对应

MyReceiver serviceReceiver;
AssetManager am;
String[] musics=new String[]{"beautiful.mp3","legendsneverdie.mp3","promise.mp3","wish.mp3"};
MediaPlayer mPlayer;
//当前状态,0x11表示没有播放,0x12代表正在播放,0x13代表暂停
int status=0x11;
//记录当前正在播放的音乐
int current=0;

onCreate函数
添加监听器、注册receiver,并向Activity发送广播

public void onCreate() {
    super.onCreate();
    am=getAssets();
    //创建BroadcastReceiver
    serviceReceiver=new MyReceiver();
    //创建IntentFilter(过滤器)
    IntentFilter filter=new IntentFilter();
    filter.addAction(MainActivity.CTL_ACTION);
    registerReceiver(serviceReceiver,filter);
    //创建MediaPlayer
    mPlayer=new MediaPlayer();
    //为MediaPlayer播放完成事件绑定监听器

    mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mp) {
            current++;
            if (current>=4)
            {
                current=0;
            }
            //发送广播通知Activity更改文本框
            Intent sendIntent = new Intent(MainActivity.UPDATE_ACTION);
            sendIntent.putExtra("current",current);
            //发送广播,将被Activity组件中的BroadcastReceiver接收
            sendBroadcast(sendIntent);
            //准备播放音乐
            prepareAndPlay(musics[current]);
        }
    });
}

MyReceiver子类,接收MainActivity发来的信息,并发送广播,定义了接收到来自MainActivity的广播后的处理过程

public class MyReceiver extends BroadcastReceiver
{
    @Override
    public void onReceive(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;
                }
                break;

            //播放上一首
            case 3:
                //原来处于没有播放或暂停状态
                if (status==0x11||status==0x13)
                {
                    if(current==0) {
                        current=3;
                        prepareAndPlay(musics[current]);
                    }
                    //准备并播放音乐
                    else {
                        current=current-1;
                        prepareAndPlay(musics[current]);
                    }
                    status=0x12;
                }
                //原来处于播放状态
                else if (status==0x12)
                {
                    //上一首//准备并播放音乐
                    if(current==0) {
                        current=3;
                        prepareAndPlay(musics[current]);
                    }
                    else {
                        current=current-1;
                        prepareAndPlay(musics[current]);
                    }
                }
                break;

            //播放下一首
            case 4:
                //原来处于没有播放或暂停状态
                if (status==0x11||status==0x13)
                {
                    if(current==3) {
                        current=0;
                        prepareAndPlay(musics[current]);
                    }   //准备并播放音乐
                    else {
                        current=current+1;
                        prepareAndPlay(musics[current]);
                    }
                    status=0x12;
                }
                //原来处于播放状态
                else if (status==0x12)
                {
                    //下一首
                    if(current==3) {
                        current=0;
                        prepareAndPlay(musics[current]);
                    }
                    else {
                        current=current+1;
                        prepareAndPlay(musics[current]);
                    }
                }
                break;
        }
        //广播通知Activity更改图标、文本框
        Intent sendIntent=new Intent(MainActivity.UPDATE_ACTION);
        sendIntent.putExtra("update",status);
        sendIntent.putExtra("current",current);
        //发送广播,将被Activity组件中的BroadcastReceiver接收
        sendBroadcast(sendIntent);
    }
}

prepareAndPlay函数,准备并播放音乐

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();
    }
}

任务成果在这里插入图片描述

源码地址

https://gitee.com/wyf234571/MyMusicBox

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值