android broadcast音乐播放器程序必须得用broadcast吗

 上传我的文档
 下载
 收藏
该文档贡献者很忙,什么也没留下。
 下载此文档
正在努力加载中...
Android_音乐播放器_功能实现和分析(整理版)
下载积分:600
内容提示:Android_音乐播放器_功能实现和分析(整理版)
文档格式:DOC|
浏览次数:99|
上传日期: 01:48:19|
文档星级:
该用户还上传了这些文档
Android_音乐播放器_功能实现和分析(整理版)
官方公共微信查看: 12498|回复: 88
改造的音乐播放器的例子(学习Service和BroadCastReceiver必用)
该用户从未签到主题帖子e币
没有eoe的账号,级别还太低,出门如何吹牛逼?
才可以下载或查看,没有帐号?
沈青海的Android Service初级应用讲解是用音乐播放器做为例子,同时也用到了BroadCastReceiver,这样就可以作为和Activity三者之间相互作用的最佳范例了。鄙人觉得视频看不清楚,贴出的代码又不全,所以加以补充,自己添加布局和按钮,编写Main.xml文件。这样工程就完整可用了,希望对您有所帮助。
感谢沈先生的视频和源码,非常值得仔细研究。
沈先生网站视频链接地址:
直接贴代码:
服务:MusicService.javapackage work.
import java.io.IOE& &
import android.app.S& &
import android.content.I& &
import android.media.MediaP& &
import android.os.B& &
import android.os.B& &
import android.os.IB& &
import android.util.L
&&
public class MusicService extends Service {& &
&&
& & // MediaPlayer实例& &
& & private MediaP& &
&&
& & // IBinder实例& &
& & private final IBinder binder = new MyBinder();& &
&&
& & /**&&
& &&&* 绑定&&
& &&&*/&&
& & @Override&&
& & public IBinder onBind(Intent intent) {& &
& && &&&playMusic();& &
& && &&&& &
& & }& &
&&
& & /**&&
& &&&* 声明Binder子类&&
& &&&*& &
& &&&* @author &&
& &&&*& &
& &&&*/&&
& & public class MyBinder extends Binder {& &
& && &&&MusicService getService() {& &
& && && && &return MusicService.& &
& && &&&}& &
&&
& & }& &
&&
& & /**&&
& &&&* 创建服务&&
& &&&*/&&
& & public void onCreate() {& &
& && &&&super.onCreate();
& && &&&Log.e(&TAG&, &onCreate&);
& && &&&playMusic();& &
& & }& &
&&
& & /**&&
& &&&* 播放&&
& &&&*/&&
& & public void playMusic() {& &
& && &&&if (player == null) {
& && &&&& & & & Log.e(&TAG&, &playMusic&);
& && && && &player = MediaPlayer.create(this, R.raw.yuanlai);& &
& && &&&}& &
& && &&&if (!player.isPlaying()) {& &
& && && && &player.start();& &
& && &&&}& &
& & }& &
&&
& & /**&&
& &&&* 暂停播放&&
& &&&*/&&
& & public void pauseMusic() {& &
& && &&&if (player != null)& &
& && && && &if (player.isPlaying()) {& &
& && && && && & & & Log.e(&TAG&, &pauseMusic&);
& && && && && & & & player.pause();
& && && && && &
& && && && &}& &
& & }& &
&&
& & /**&&
& &&&* 停止播放&&
& &&&*/&&
& & public void stopMusic() {& &
& && &&&if (player != null) {
& && &&&& & & & Log.e(&TAG&, &stopMusic&);
& && && && &player.stop();& &
& && && && &try {& &
& && && && && & // 在调用stop后如果需要再次通过start进行播放,需要之前调用prepare函数& &
& && && && && & player.prepare();& &
& && && && &} catch (IOException ex) {& &
& && && && && & ex.printStackTrace();& &
& && && && &}& &
& && &&&}& &
& & }& &
&&
& & /**&&
& &&&* 开始播放&&
& &&&*/&&
& & public void onStart(Intent intent, int startId) {& &
& && &&&super.onStart(intent, startId);& &
& && &&&Log.e(&TAG&, &onStart&);
& && &&&if (intent != null) {& &
& && && && &Bundle bundle = intent.getExtras();& &
& && && && &if (bundle != null) {& &
& && && && && & int op = bundle.getInt(&op&);& &
& && && && && & switch (op) {& &
& && && && && & case 1:& &
& && && && && && &&&playMusic();& &
& && && && && && &&&& &
& && && && && & case 2:& &
& && && && && && &&&pauseMusic();& &
& && && && && && &&&& &
& && && && && & case 3:& &
& && && && && && &&&stopMusic();& &
& && && && && && &&&& &
& && && && && & }& &
& && && && &}& &
& && &&&}& &
& & }& &
&&
& & /**&&
& &&&* 销毁服务&&
& &&&*/&&
& & public void onDestroy() {& &
& && &&&super.onDestroy();&&
& && &&&Log.e(&TAG&, &onDestroy&);
& && &&&if (player != null) {& &
& && && && &player.stop();& &
& && && && &player.release();& &
& && &&&}& &
& & }& &
&&
}&&复制代码广播接收器:MusicReceiver.javapackage work.
import android.content.BroadcastR& &
import android.content.C& &
import android.content.I& &
import android.os.B& &
import android.util.L
/**&&
*/&&
public class MusicReceiver extends BroadcastReceiver {& &
& & C& &
&&
& & @Override&&
& & public void onReceive(Context context, Intent intent) {
& & & & & & Log.e(&TAG&, &onReceive&);
& && &&&this.context =& &
& && &&&Intent it = new Intent(&work.service.MUSIC_SERVICE_SERVICE&);& &
& && &&&Bundle bundle = intent.getExtras();& &
& && &&&it.putExtras(bundle);& &
& && &&&if (bundle != null) {& &
& && && && &int op = bundle.getInt(&op&);& &
& && && && &Log.e(&TAG&, &Receive&+op+&...........&);
& && && && &if (op == 4) {& &
& && && && && & context.stopService(it);& &
& && && && &} else {& &
& && && && && & context.startService(it);& &
& && && && && & // context.bindService(it, mConnection,& &
& && && && && & // Context.BIND_AUTO_CREATE);& &
& && && && &}& &
& && &&&}& &
& & }& &
}&&
复制代码界面Activity类:ExampleServiceRequest.javapackage work.
import android.app.A& &
import ponentN
import android.content.I& &
import android.content.ServiceC
import android.os.B& &
import android.os.IB
import android.util.L
import android.view.V& &
import android.view.View.OnClickL& &
import android.widget.B& &
import android.widget.LinearL
/**&&
*/&&
public class ExampleServiceRequest extends Activity implements OnClickListener {& &
& & Button btnS& &
& & Button btnP& &
& & Button btnP& &
& & Button btnS& &
& & Button btnS& &
& & Button btnE& &
&&
& & /** Called when the activity is first created. */&&
& & @Override&&
& & public void onCreate(Bundle savedInstanceState) {& &
& && &&&super.onCreate(savedInstanceState);& &
//& && &&&setContentView(R.layout.main);& &
& && &&&//
& && &&&LinearLayout l=new LinearLayout(this);
& && &&&l.setOrientation(LinearLayout.VERTICAL);//垂直布局
& && &&&LinearLayout.LayoutParams ll=new LinearLayout.LayoutParams(
& && &&&& & & & & & & & LinearLayout.LayoutParams.FILL_PARENT,
& && &&&& & & & & & & & LinearLayout.LayoutParams.WRAP_CONTENT
& && &&&);
& && &&&
& && &&&
& && &&&//
& && &&&Button btnStartservice = new Button(this);
& && &&&btnStartservice.setId(01);
& && &&&btnStartservice.setText(&开始服务&);
& && &&&btnStartservice.setOnClickListener(this);
& && &&&l.addView(btnStartservice, ll);
& && &&&//& &
& && &&&Button btnPlay = new Button(this);
& && &&&btnPlay.setId(02);
& && &&&btnPlay.setText(&播放音乐&);
& && &&&btnPlay.setOnClickListener(this);
& && &&&l.addView(btnPlay, ll);
& && &&&//& &
& && &&&Button btnPause = new Button(this);
& && &&&btnPause.setId(03);
& && &&&btnPause.setText(&暂停&);
& && &&&btnPause.setOnClickListener(this);
& && &&&l.addView(btnPause, ll);
& && &&&//& &
& && &&&Button btnStop =new Button(this);
& && &&&btnStop.setId(04);
& && &&&btnStop.setText(&停止&);
& && &&&btnStop.setOnClickListener(this);
& && &&&l.addView(btnStop, ll);
& && &&&//& &
& && &&&Button btnStopservice =new Button(this);
& && &&&btnStopservice.setId(05);
& && &&&btnStopservice.setText(&停止服务&);
& && &&&btnStopservice.setOnClickListener(this);
& && &&&l.addView(btnStopservice, ll);
& && &&&//& &
& && &&&Button btnExit =new Button(this);
& && &&&btnExit.setId(06);
& && &&&btnExit.setText(&退出&);
& && &&&btnExit.setOnClickListener(this);
& && &&&l.addView(btnExit, ll);
& && &&&
& && &&&
& && &&&this.setContentView(l);
& & }& &
&&
& & /**&&
& &&&* 点击处理
& &&&*/&&
& & public void onClick(View v) {
& & & & & &
& & & & & && &
& & & & & &
& && &&&int op = -1;& &
& && &&&
& && &&&if (v==(findViewById(01))){
& && &&&& & & &
& && && && &op = 0;&&}
& && &&&else if (v.equals(findViewById(02)))& &
& && && && &op = 1;& &
& && &&&else if (v.equals(findViewById(03)))& &
& && && && &op = 2;& &
& && &&&else if (v.equals(findViewById(04)))& &
& && && && &op = 3;& &
& && &&&else if (v.equals(findViewById(05)))& &
& && && && &op = 4;& &
& && &&&else if (v.equals(findViewById(06))) {& &
& && && && &this.finish();& &
& && && && && &
& && &&&}& &
& && &&&Log.e(&TAG&, &onClick...&+op+&...........&);
& && &&&// 构造数据&&
& && &&&Bundle bundle = new Bundle();& &
& && &&&bundle.putInt(&op&, op);& &
& && &&&Intent intent = new Intent(&work.service.MUSIC_SERVICE_BROADCAST&);
& && &&&intent.putExtras(bundle);& &
& && &&&// 发送广播& &
& && &&&sendBroadcast(intent);
& && &&&
& && &&&Log.e(&TAG&, &Broadcast&+op+&...........&);
& & }
& & *//**
& &&&*&&服务实例
& &&&*//*
& & private MusicService serviceB
& & *//**
& &&&* 当服务和Activity连接时调用函数
& &&&*
& &&&*//*
& & private ServiceConnection mConnection=new ServiceConnection(){
& & & & & & & & public void onServiceConnected(ComponentName name, IBinder service) {
& & & & & & & & & & & & serviceBinder=((MusicService.MyBinder)service).getService();//???
& & & & & & & & & & & & if(serviceBinder!=null){
& & & & & & & & & & & & & & & & serviceBinder.playMusic();
& & & & & & & & & & & & }
& & & & & & & & & & & &
& & & & & & & & }
& & & & & & & & *//**
& & & & & & & &&&* 当服务和Activity断开时调用
& & & & & & & &&&*//*
& & & & & & & & public void onServiceDisconnected(ComponentName name) {
& & & & & & & & & & & & serviceBinder=
& & & & & & & & & & & &
& & & & & & & & }
& & & & & &
& & };*/
}&&
复制代码主配置文件:AndroidManifest.xml&?xml version=&1.0& encoding=&utf-8&?&
&manifest xmlns:android=&/apk/res/android&
& && &package=&work.service&
& && &android:versionCode=&1&
& && &android:versionName=&1.0&&
& & &application android:icon=&@drawable/icon& android:label=&@string/app_name&&
& & &activity android:name=&ExampleServiceRequest&&
& & & & & & &intent-filter&
& && && && && & &action android:name=&android.intent.action.MAIN& /&
& && && && && & &category android:name=&android.intent.category.LAUNCHER& /&
& && &&&&/intent-filter&
& &
& & &/activity&
& &
& & & & &service android:name=&MusicService&&
& & & & & & & & &intent-filter&
& && && && && & &action android:name=&work.service.MUSIC_SERVICE_SERVICE& /&
& && && && && & &category android:name=&android.intent.category.defult& /&
& && && && && &
& && &&&&/intent-filter&
& & & & &/service&
& & & &
& & & & &receiver android:name=&MusicReceiver&&
& & & & & & & & &intent-filter&
& & & & & & & & & & & & &action android:name=&work.service.MUSIC_SERVICE_BROADCAST&/&
& & & & & & & & &/intent-filter&
& & & &
& & & & &/receiver&
&/application&
& & &uses-sdk android:minSdkVersion=&7& /&
&/manifest& 复制代码工程文件,如果不会贴的就倒吧,其实不必破费呵呵
操,我的p3文件太大了,传不上来,算了,想要的都贴自己工程里吧,练练手,我没用其他的xml,都是自己在代码里布局的
签到天数: 3 天连续签到: 1 天[LV.2]偶尔看看I主题帖子e币
该用户从未签到主题帖子e币
是流媒体不?
该用户从未签到主题帖子e币
群里看到的,帮顶
该用户从未签到主题帖子e币
谢谢,你们真是好同志
这么多人看就没人说两句,我还想挣点积分呢:'(
该用户从未签到主题帖子e币
该用户从未签到主题帖子e币
该用户从未签到主题帖子e币
你的R.raw.yuanlai文件在哪啊,这个没有怎么用啊
该用户从未签到主题帖子e币
歌曲的&&自己随便加一首歌 并且改成R.raw.歌曲名
该用户从未签到主题帖子e币
只是播放mp3的例子程序呵呵
该用户从未签到主题帖子e币
nongchaoshen
8楼说的对,那个原来你也在这里.mp3太大了,工程文件传不上来。
大家用的话,只替换这个文件就好了,其他的不用改,我不用xml布局
该用户从未签到主题帖子e币
支持,支持!嘿嘿
该用户从未签到主题帖子e币
还真不错的呀。。
签到天数: 203 天连续签到: 1 天[LV.7]常住居民III主题帖子e币
该用户从未签到主题帖子e币
谢谢,有空慢慢研究
推荐阅读热门话题
61882417416379326279277260256251226218210206715
半小时前半小时前3&小时前4&小时前5&小时前昨天&23:52昨天&22:59昨天&22:21昨天&22:19昨天&21:35昨天&20:45昨天&16:56昨天&16:44昨天&15:12昨天&15:09昨天&11:03
Powered byAndroid应用界面开发——BroadcastReceiver(实现基于Service的音乐播放器) - 简书
<div class="fixed-btn note-fixed-download" data-toggle="popover" data-placement="left" data-html="true" data-trigger="hover" data-content=''>
写了43540字,被94人关注,获得了283个喜欢
Android应用界面开发——BroadcastReceiver(实现基于Service的音乐播放器)
BroadcastReceiver:广播接收者,Android四大组件之一,这个组件本质上就是一个全局监听器,用于监听系统全局的广播消息。由于BroadcastReceiver是一个全局监听器,因此它可以方便的实现系统中不同组件之间的通信。
BroadcastReceiver简介
BroadcastReceiver用于接收程序(开发者开发的程序和系统程序)发出的Broadcast Intent,程序启动BroadcastReceiver需要两步:
创建需要启动的BroadcastReceiver的Intent。
调用Context的sendBroadcast()或sendOrderedBroadcast()方法来启动指定的BroadcastReceiver。
实现BroadcastReceiver只要重写BroadcastReceiver的onReceive(Context context, Intent intent)方法即可。
实现了BroadcastReceiver,接着应该指定该BroadcastReceiver能匹配的Intent,有两种方式:
静态注册:
在AndroidManifest.xml中配置:
&receiver android:name=".MyReceiver"&
&intent-filter&
&action android:name="com.trampcr.musicplayer.PLAY_ACTION"/&
&/intent-filter&
&/receiver&
动态注册:
使用代码进行指定,调用BroadcastReceiver的Context的registerReceiver(BroadcastReceiver receiver, IntentFilter filter)方法指定:
IntentFilter intentFilter = new IntentFilter("com.trampcr.musicplayer.PLAY_ACTION");
MyReceiver receiver = new MyReceiver();
registerReceiver(receiver, intentFilter);
每次系统广播事件发生后,系统会创建对应的BroadcastReceiver实例,并自动触发它的onReceiver()方法,如果onReceiver()方法不能在10秒内完成,Android就会认为该程序无响应(所以onReceiver()方法中不能进行耗时操作)。onReceiver()方法执行完后,BroadcastReceiver实例就会被销毁。
如果需要根据Broadcast完成比较耗时的操作,则应该考虑通过Intent启动一个Service来完成,不考虑使用新线程完成耗时操作的原因:BroadcastReceiver本身的生命周期很短,很可能子线程还没有结束,BroadcastReceiver就已经退出了。
调用Context的sendBroadcast(Intent intent)方法发送广播,这条广播将会启动intent参数所对应的BroadcastReceiver。
该程序的Activity界面包含一个按钮,用于向外发送广播。代码如下:
public class MainActivity extends AppCompatActivity {
private Button mSendB
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSendBroadcast = (Button) findViewById(R.id.send_broadcast);
mSendBroadcast.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent();
//设置Intent的Action属性
intent.setAction("com.trampcr.musicplayer.PLAY_ACTION");
intent.putExtra("msg", "simple message");
//发送广播
sendBroadcast(intent);
上述程序用于创建一个Intent对象,并使用该Intent对象对外发送了一条广播。
发送了广播,就得接收广播,接收广播代码如下:
public class MyReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
String[] msg = intent.getStringArrayExtra("msg");
Toast.makeText(context, "接收的Intent的Action为:" + action + "\n消息内容是" + msg, Toast.LENGTH_SHORT).show();
当符合该MyReceiver的广播出现时,MyReceiver的onReceiver()方法就会被触发,从而在该方法中显示广播所携带的消息。
发送广播时Intent的Action为com.trampcr.musicplayer.PLAY_ACTION,这就需要配置MyReceiver应监听Action为该字符串的Intent,在AndroidManifest.xml中配置:
&receiver android:name=".MyReceiver"&
&intent-filter&
&action android:name="com.trampcr.musicplayer.PLAY_ACTION"/&
&/intent-filter&
&/receiver&
点击发送广播按钮,可以看到收到广播的提示,如下:
广播分为两种:
Normal Broadcast(普通广播):完全异步,可以在同一时刻被所有接收者接收到。
sendBroadcast():发送Normal Broadcast。
Ordered Broadcast(有序广播):接收者按预先声明的优先级依次接收Broadcast。
优先级声明在&intent-filter.../&元素的android:priority属性中,数越大优先级越高。
Ordered Broadcast接收者可以调用abortBroadcast()方法终止Broadcast Intent的传播,一旦终止,后面的接收者就无法接收到Broadcast。
sendOrderedBroadcast():发送Ordered Broadcast。
上面发送广播中举了一个发送普通广播的例子,这里再举一个发送有序分广播的例子:
该程序的Activity界面只有一个按钮,用于发送一条有序广播,代码如下:
public class MainActivity extends AppCompatActivity {
private Button mSendB
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSendBroadcast = (Button) findViewById(R.id.send_broadcast);
mSendBroadcast.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent();
//设置Intent的Action属性
intent.setAction("com.trampcr.musicplayer.PLAY_ACTION");
intent.putExtra("msg", "simple message");
//发送有序广播
sendOrderedBroadcast(intent, null);
代码中指定了Intent的Action属性,再调用sendOrderedBroadcast()方法来发送有序广播。对于有序广播,它会按优先级依次触发每个BroadcastReceiver的onReceiver()方法。
第一个BroadcastReceiver代码:
public class MyReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
String msg = intent.getStringExtra("msg");
Toast.makeText(context, "接收的Intent的Action为:" + action + "\n消息内容是" + msg, Toast.LENGTH_SHORT).show();
//创建一个Bundle对象,并存入数据
Bundle bundle = new Bundle();
bundle.putString("first", "第一个BroadcastReceiver存入的消息");
//将bundle放入结果中
setResultExtras(bundle);
//取消Broadcast的继续传播
//abortBroadcast();
MyReceiver不仅处理了它所接收的消息,而且向处理结果中存入了key为first的消息,这个消息将可以被第二个BroadcastReceiver解析出来。
abortBroadcast()用于取消广播,如果这条代码生效,那么优先级比MyReceiver低的BroadcastReceiver都将不会被触发。
在AndroidManifest.xml中部署该BroadcastReceiver,并指定其优先级为20,代码如下:
&receiver android:name=".MyReceiver"&
&intent-filter android:priority="20"&
&action android:name="com.trampcr.musicplayer.PLAY_ACTION"/&
&/intent-filter&
&/receiver&
接下来提供第二个BroadcastReceiver,将会解析前一个BroadcastReceiver存入的key为first的消息,代码如下:
public class MyReceiver2 extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
Bundle bundle = getResultExtras(true);
//解析前一个BroadcastReceiver所存入的key为first的消息
String first = bundle.getString("first");
Toast.makeText(context, "第一个Broadcast存入的消息为:" + first, Toast.LENGTH_SHORT).show();
解析出前一个BroadcastReceiver存入结果中的key为first的消息。
在AndroidManifest.xml中配置MyReceiver2的优先级为0,如下:
&receiver android:name=".MyReceiver2"&
&intent-filter android:priority="0"&
&action android:name="com.trampcr.musicplayer.PLAY_ACTION" /&
&/intent-filter&
&/receiver&
先注释掉abortBroadcast(),点击发送有序广播按钮,可以看到先显示第一个广播接收器中的内容,再显示第二个广播接收器中的内容,如下:
如果不注释abortBroadcast(),将会阻止消息广播,消息将传不到MyReceiver2。
广播接收器除了可以接收用户发送的广播,还可以接收系统广播,常用的系统广播如下:
ACTION_TIME_CHANGED:系统时间被改变。
ACTION_DATE_CHANGED:系统日期被改变。
ACTION_TIMEZONE_CHANGED:系统时区被改变。
ACTION_BOOT_COMPLETED:系统启动完成。
ACTION_PACKAGE_ADDED:系统添加包。
ACTION_PACKAGE_CHANGED:系统的包改变。
ACTION_PACKAGE_REMOVED:系统的包被删除。
ACTION_PACKAGE_RESTARTED:系统的包被重启。
ACTION_PACKAGE_DATA_CLEARED:系统的包数据被清空。
ACTION_BATTERY_CHANGED:电池电量改变。
ACTION_BATTERY_LOW:电池电量低。
ACTION_POWER_CONNECTED:系统连接电源。
ACTION_POWER_DISCONNECTED:系统与电源断开。
ACTION_SHUTDOWN:系统被关闭。
基于Service的音乐播放器
这里开发一个基于Service的音乐播放器,音乐由后台运行的Service负责播放,当后台的播放状态发生变化时,程序将会通过发送广播通知前台Activity更新界面;当点击Activity的界面按钮时,系统将通过发送广播通知后台Service来改变播放状态。
前台Activity界面有两个按钮,分别用于控制播放/暂停、停止,另外还有两个文本框,用于显示正在播放的歌曲名、歌手名。前台Activity的代码如下:
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private ImageButton mS
private ImageButton mS
private TextView mMusicN
private TextView mSongerN
private ActivityReceiver mActivityR
public static final String CTL_ACTION = "com.trampcr.action.CTL_ACTION";
public static final String UPDATE_ACTION = "com.trampcr.action.UPDATE_ACTION";
//定义音乐播放状态,0x11代表没有播放,0x12代表正在播放,0x13代表暂停
int status = 0x11;
String[] musicNames = new String[]{"完美生活", "那一年", "故乡"};
String[] songerNames = new String[]{"许巍", "许巍", "许巍"};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mStart = (ImageButton) findViewById(R.id.start);
mStop = (ImageButton) findViewById(R.id.stop);
mMusicName = (TextView) findViewById(R.id.music_name);
mSongerName = (TextView) findViewById(R.id.songer_name);
mStart.setOnClickListener(this);
mStop.setOnClickListener(this);
mActivityReceiver = new ActivityReceiver();
//创建IntentFilter
IntentFilter filter = new IntentFilter();
//指定BroadcastReceiver监听的Action
filter.addAction(UPDATE_ACTION);
//注册BroadcastReceiver
registerReceiver(mActivityReceiver, filter);
Intent intent = new Intent(MainActivity.this, MusicService.class);
//启动后台Service
startService(intent);
public class ActivityReceiver extends BroadcastReceiver {
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){
mMusicName.setText(musicNames[current]);
mSongerName.setText(songerNames[current]);
switch (update){
case 0x11:
mStart.setBackgroundResource(R.drawable.play);
status = 0x11;
//控制系统进入播放状态
case 0x12:
//在播放状态下设置使用暂停图标
mStart.setBackgroundResource(R.drawable.pause);
status = 0x12;
case 0x13:
//在暂停状态下设置使用播放图标
mStart.setBackgroundResource(R.drawable.play);
status = 0x13;
public void onClick(View v) {
Intent intent = new Intent(CTL_ACTION);
switch (v.getId()){
case R.id.start:
intent.putExtra("control", 1);
case R.id.stop:
intent.putExtra("control", 2);
//发送广播,将被Service中的BroadcastReceiver接收到
sendBroadcast(intent);
ActivityReceiver()用于响应后台Service所发出的广播,该程序将会根据广播Intent里的消息来改变播放状态,并更新程序界面中按钮的图标。
onClick中根据点击的按钮发送广播,发送广播时会把所按下的按钮标识发送出来。
接下来是后台Service,会在播放状态发生改变时对外发送广播。代码如下:
public class MusicService extends Service {
MyReceiver serviceR
AssetManager mAssetM
String[] musics = new String[]{"prefectLife.mp3", "thatYear.mp3", "country.mp3"};
MediaPlayer mMediaP
int status = 0x11;
int current = 0; // 记录当前正在播放的音乐
public IBinder onBind(Intent intent) {
public void onCreate() {
super.onCreate();
mAssetManager = getAssets();
serviceReceiver = new MyReceiver();
//创建IntentFilter
IntentFilter filter = new IntentFilter();
filter.addAction(MainActivity.CTL_ACTION);
registerReceiver(serviceReceiver, filter);
//创建MediaPlayer
mMediaPlayer = new MediaPlayer();
//为MediaPlayer播放完成事件绑定监听器
mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
current++;
if (current &= 3) {
current = 0;
//发送广播通知Activity更改文本框
Intent sendIntent = new Intent(MainActivity.UPDATE_ACTION);
sendIntent.putExtra("current", current);
//发送广播,将被Activity中的BroadcastReceiver接收到
sendBroadcast(sendIntent);
//准备并播放音乐
prepareAndPlay(musics[current]);
public class MyReceiver extends BroadcastReceiver {
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){
mMediaPlayer.pause();
status = 0x13; // 改变为暂停状态
//原来处于暂停状态
else if (status == 0x13){
mMediaPlayer.start();
status = 0x12; // 改变状态
//停止声音
//如果原来正在播放或暂停
if (status == 0x12 || status == 0x13){
//停止播放
mMediaPlayer.stop();
status = 0x11;
//广播通知Activity更改图标、文本框
Intent sendIntent = new Intent(MainActivity.UPDATE_ACTION);
sendIntent.putExtra("update", status);
sendIntent.putExtra("current", current);
//发送广播,将被Activity中的BroadcastReceiver接收到
sendBroadcast(sendIntent);
private void prepareAndPlay(String music) {
//打开指定的音乐文件
AssetFileDescriptor assetFileDescriptor = mAssetManager.openFd(music);
mMediaPlayer.reset();
//使用MediaPlayer加载指定的声音文件
mMediaPlayer.setDataSource(assetFileDescriptor.getFileDescriptor(), assetFileDescriptor.getStartOffset(), assetFileDescriptor.getLength());
mMediaPlayer.prepare(); // 准备声音
mMediaPlayer.start(); // 播放
} catch (IOException e) {
e.printStackTrace();
MyReceiver用于接收前台Activity所发出的广播,并根据广播的消息内容改变Service的播放状态,当播放状态改变时,该Service对外发送一条广播,广播消息将会被前台Activity接收,前台Activity将会根据广播消息更新界面。
为了让该音乐播放器能按顺序依次播放歌曲,程序为MediaPlayer增加了OnCompletionListener监听器,当MediaPlayer播放完成后将自动播放下一首歌曲。
运行程序,效果图如下:
如果觉得对您有用,请随意
打开微信“扫一扫”,打开网页后点击屏幕右上角分享按钮
被以下专题收入,发现更多相似内容:
@IT 专题 由 IT大分类,转定位于IT·互联网行业观察与思考,数码产品极客体验。
主编:向右奔跑 http://www.ji...
· 170448人关注
玩转简书的第一步,从这个专题开始。
想上首页热门榜么?好内容想被更多人看到么?来投稿吧!如果被拒也不要灰心哦~入选文章会进一个队...
· 136826人关注
分享Android开发的知识,教程,解析,前沿信息,都可以,欢迎大家投稿~
内容可搞笑,可逗比,另外欢迎申请管理员
· 22723人关注
如果觉得对您有用,请随意
选择支付方式:}

我要回帖

更多关于 android 仿音乐播放器 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信