效果图大概如下
这个功能的完成主要是广播和服务的应用
1.首先需要创建一个asset文件夹用来放音乐文件
然后将MP3文件拖入这个文件夹
2.在mainfest里添加一行代码:
<service android:name=".MusicService"></service>
3.布局设置
首先需要一个开始/暂停按钮和停止按钮,因此我们要在网上找到下载这三个图标文件放入drawable文件夹中,布局中在LinearLayout中添加两个ImageButton
然后除了这两个按钮旁边应该还要一行显示歌名和歌手的说明,因此还需要一个LinearLayout并添加两个textview
调整LinearLayout大小、位置、方向,我的代码示例如下
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<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"/>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25sp"
android:textColor="#9C27B0"
android:ellipsize="marquee"
android:layout_weight="1"
android:marqueeRepeatLimit="marquee_forever"/>
<TextView
android:id="@+id/author"
android:textSize="25sp"
android:gravity="center_vertical"
android:layout_weight="1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
</LinearLayout>
再写MainActivity和MusicService
MainActivity设置可以点击按钮,不同状态下按钮图标的切换,代码如下
package com.example.mymusicbox;
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.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.TextView;
public class MainActivity extends Activity implements OnClickListener
{
// 获取界面中显示歌曲标题、作者文本框
TextView title, author;
// 播放/暂停、停止按钮
ImageButton play, stop;
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[] {
"BeautifulGirl", "我的一个道姑朋友", "牛奶面包" };
String[] authorStrs = new String[] {
"HAHA & Skull", "双笙", "杨紫" }