本文开发一个基于Service的音乐播放器,音乐由后台运行的Service负责播放,当后台的播放状态发生变化时,程序将会通过发送广播通知前台Activity更新界面;当点击Activity的界面按钮时,系统将通过发送广播通知后台Service来改变播放状态。

前台Activity界面有两个按钮,分别用于控制播放/暂停、停止,另外还有两个文本框,用于显示正在播放的歌曲名、歌手名。前台Activity的代码如下:

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

private ImageButton mStart;

private ImageButton mStop;

private TextView mMusicName;

private TextView mSongerName;

private ActivityReceiver mActivityReceiver;

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[]{"许巍", "许巍", "许巍"};

@Override

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 {

@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){

mMusicName.setText(musicNames[current]);

mSongerName.setText(songerNames[current]);

}

switch (update){

case 0x11:

mStart.setBackgroundResource(R.drawable.play);

status = 0x11;

break;

//控制系统进入播放状态

case 0x12:

//在播放状态下设置使用暂停图标

mStart.setBackgroundResource(R.drawable.pause);

status = 0x12;

break;

case 0x13:

//在暂停状态下设置使用播放图标

mStart.setBackgroundResource(R.drawable.play);

status = 0x13;

break;

}

}

}

@Override

public void onClick(View v) {

Intent intent = new Intent(CTL_ACTION);

switch (v.getId()){

case R.id.start:

intent.putExtra("control", 1);

break;

case R.id.stop:

intent.putExtra("control", 2);

break;

}

//发送广播,将被Service中的BroadcastReceiver接收到

sendBroadcast(intent);

}

}

ActivityReceiver()用于响应后台Service所发出的广播,该程序将会根据广播Intent里的消息来改变播放状态,并更新程序界面中按钮的图标。

onClick中根据点击的按钮发送广播,发送广播时会把所按下的按钮标识发送出来。

接下来是后台Service,会在播放状态发生改变时对外发送广播。代码如下:

public class MusicService extends Service {

MyReceiver serviceReceiver;

AssetManager mAssetManager;

String[] musics = new String[]{"prefectLife.mp3", "thatYear.mp3", "country.mp3"};

MediaPlayer mMediaPlayer;

int status = 0x11;

int current = 0; // 记录当前正在播放的音乐

@Nullable

@Override

public IBinder onBind(Intent intent) {

return null;

}

@Override

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() {

@Override

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 {

@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){

//暂停

mMediaPlayer.pause();

status = 0x13; // 改变为暂停状态

}

//原来处于暂停状态

else if (status == 0x13){

//播放

mMediaPlayer.start();

status = 0x12; // 改变状态

}

break;

//停止声音

case 2:

//如果原来正在播放或暂停

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) {

try {

//打开指定的音乐文件

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播放完成后将自动播放下一首歌曲。

运行程序,效果图如下:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

android服务绑定音乐播放器,Android基于Service的音乐播放器相关推荐

  1. android后台音乐,Android基于service实现音乐的后台播放功能示例

    本文实例讲述了Android基于service实现音乐的后台播放功能.分享给大家供大家参考,具体如下: Service是一个生命周期长且没有用户界面的程序,当程序在各个activity中切换的时候,我 ...

  2. android服务绑定音乐播放器,Android开发【04-21求助贴】使用后台服务的音乐播放器...

    该楼层疑似违规已被系统折叠 隐藏此楼查看此楼 import android.Manifest; import android.content.pm.PackageManager; import and ...

  3. 基于python的音频播放器_基于python实现音乐播放器代码实例

    基于python实现音乐播放器代码实例,一首,函数,按钮,布局,音乐 基于python实现音乐播放器代码实例 易采站长站,站长之家为您整理了基于python实现音乐播放器代码实例的相关内容. 核心播放 ...

  4. android 服务保活之白名单,Android 后台运行白名单,优雅实现保活

    原标题:Android 后台运行白名单,优雅实现保活 保活现状 我们知道,Android 系统会存在杀后台进程的情况,并且随着系统版本的更新,杀进程的力度还有越来越大的趋势.系统这种做法本身出发点是好 ...

  5. 仿迅雷播放器教程 -- 基于VLC的MFC播放器 (6)

    代码下载: http://download.csdn.net/detail/qq316293804/6409417 昨天的教程里写着预计MFC播放器会隔得久一点,但是今晚仔细看了下VLC的常用代码,发 ...

  6. 仿迅雷播放器教程 -- 基于VLC的C++播放器 (4)

    经过前面的介绍,想必大家对VLC和ffmpeg都有一定印象了,还记得学习ffmpeg多么蛋疼吗?那么VLC会不会也这么蛋疼呢? 那么我们来看一段 官方的Demo,Alberl精简了Demo,只留下了主 ...

  7. python装饰器类-基于类的python装饰器

    python装饰器函数其实是这样一个接口约束,它必须接受一个callable对象作为参数,然后返回一个callable对象.在Python中一般callable对象都是函数,但也有例外.只要某个对象重 ...

  8. html抢答器代码,基于FPGA的四路抢答器的Verilog HDL代码.doc

    基于FPGA的四路抢答器的Verilog HDL代码.doc module qiangda4(clk,clr,inputEn,add,stu,inputL1,inputL2,inputL3,input ...

  9. android服务绑定异步,Android中异步类AsyncTask用法总结

    本文总结分析了Android中异步类AsyncTask用法.分享给大家供大家参考,具体如下: 最近整理笔记的时候,看到有关AsyncTask不是很理解,重新疏导了一下,有在网上找了一些资料,个人不敢独 ...

最新文章

  1. JAVA实现用两个栈来实现一个队列,完成队列的Push和Pop操作(《剑指offer》)
  2. 第24天学习Java的笔记-接口Interface
  3. MFC中如何让一个CStatic控件响应消息
  4. 你应该如何选择笔记软件?
  5. Android UI(四)云通讯录项目之云端更新进度条实现
  6. python 3中 的subprocess
  7. ipfs操作mysql_IPFS 使用入门
  8. 通用sqlserver分页存储过程
  9. oj2894(贝尔曼福特模板)
  10. 【汇编语言】通用数据处理指令——数据传送类指令
  11. java bean_透彻理解JavaBean视频教程 - JavaWeb - Java - 私塾在线 - 只做精品视频课程服务...
  12. Javaweb图书管理系统的设计与实现(含毕业设计)
  13. 月销13485台的理想ONE,到底做对了哪些事儿?
  14. MyBatis 的一级缓存与二级缓存
  15. 微软梁念坚:六个新潮流推动IT行业发展
  16. Unity URP 渲染管线着色器编程 104 之 镜头光晕(lensflare)的实现
  17. 流行和声(2)Major6和弦
  18. 网红KOL营销怎么做?如何寻找合适的网红KOL?
  19. vue实现pc端扫码登录
  20. 电脑开机时多出来个 Windows PE 操作系统选项? 如何去除掉?

热门文章

  1. java多线程并发排序-睡眠排序大法
  2. 浮栅场效应管 符号_电子元器件—场效应管
  3. 灵云工作室计算机,灵云全方位人工智能开放平台:AI赋能 共享产业未来
  4. phpstudy安装及使用教程
  5. 女孩用自己的×××身来换取男友的健康
  6. [附源码]Nodejs计算机毕业设计全国乡村振兴信息服务平台Express(程序+LW)
  7. 游戏论坛项目设计分析
  8. 第一次课 学习之初 1.1~1.16
  9. 统计02:怎样描绘数据
  10. 2022年同济大学计算机考研初试成绩查询时间及入口