文章目录
一、知识要点
使用Android Studio编写一个简单的音乐盒,需要用到BroadcastReceiver组件,它是Android的四大组件之一,用来编写广播接收者程序,对广播做出响应。要求音乐盒能够实现上一首、播放/暂停、停止、下一首的功能,同时显示播放歌曲的简单信息。
Broadcast(广播机制) 是一种广泛运用的应用程序之间传输信息的机制,而 BroadcastReceiver(广播接收器) 则是用于接收来自系统和应用的广播对并对其进行响应的组件,Android中我们要发送的广播内容是一个Intent,这个Intent中可以携带我们要传送的数据。创建一个广播接收器非常简单,只需要继承 BroadcastReceiver,并重写onReceive()即可。BroadcastReceiver也是四大组件之一,所以我们也需要对BroadcastReceiver进行注册,不同于其他四大组件,BroadcastReceiver有两种注册方式,分别是静态注册和动态注册。
而之所以要用广播机制来制作手机音乐盒;是因为现在的都是在线音乐盒,在我们点击播放一首歌曲的时候,要从服务器拿数据,然后播放,这其实不止一个流程,可以理解为多线程的,普通的函数调用实现效果不好。而广播机制和Binder机制不一样的地方在于,广播的发送者和接收者事先是不需要知道对方的存在的,这样带来的好处便是系统的各个组件可以松耦合地组织在一起,这样系统就具有高度的可扩展性,容易与其它系统进行集成。
二、xml代码
activity_main.xml
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:orientation="horizontal"
xmlns:android="http://schemas.android.com/apk/res/android">
<ImageButton
android:layout_margin="10dp"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:src="@drawable/play"
android:id="@+id/play"/>
<ImageButton
android:layout_margin="10dp"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:src="@drawable/stop"
android:id="@+id/stop"/>
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="@+id/title"
android:marqueeRepeatLimit="marquee_forever"
android:layout_weight="1"
android:ellipsize="marquee"
android:textColor="#9C27B0"
android:textSize="25sp"
android:text="@string/app_name"/>
<TextView
android:layout_height="wrap_content"
android:layout_width&