android 音乐播放 启动方式 (3)服务通过发送广播来控制activity显示进度等
2017-07-11 10:19
766 查看
原项目在这里 https://github.com/LineChen/XimalayaFM
播放列表存放在里application中,这个地方可以优化
1
PlayService中:播放路径从intent中获取
2 activity 中
/**
*通知服务播放对应位置的音乐
*@paramposition
*/
private voidplayMusic(intposition,booleanplayNew){
Intent serviceIntent =newIntent(this,
PlayService.class);
serviceIntent.putExtra(Constants.INTENT_EXTRA_CHANGE_MUSIC,
playNew);
if(playNew){
if(position
> -1&& position < FMApplication.INSTANCE.getPlayList().size())
serviceIntent.putExtra(Constants.INTENT_EXTRA_MUSIC_POSITION,
position);
}
startService(serviceIntent);
}
caseR.id.ac_notify_play_ib:
//TODO点击播放按钮处理
isPlaying=
!isPlaying;
Log.e("--============","activity:isPlaying
: "+isPlaying);
playMusic(-1,false);
//更新playUI
updatePlayUI(isPlaying);
break;
*******************-----------*********************
caseR.id.ac_notify_pre_ib:
//TODO点击上一首按钮处理
if(--curPlayPosition==
-1)
curPlayPosition=
FMApplication.INSTANCE.getPlayList().size() -
1;
playMusic(curPlayPosition,true);
notifyPlayIb.setEnabled(false);
notifyPlayIb.setBackgroundResource(R.drawable.notify_pause_selector);
updateOtherUI(curPlayPosition);
break;
caseR.id.ac_notify_next_ib:
//TODO点击下一首按钮处理
if(++curPlayPosition==
FMApplication.INSTANCE.getPlayList().size())
curPlayPosition=0;
playMusic(curPlayPosition,true);
notifyPlayIb.setEnabled(false);
notifyPlayIb.setBackgroundResource(R.drawable.notify_pause_selector);
updateOtherUI(curPlayPosition);
break;
**********************************
//-------------------------seekBar回调方法
@Override
public voidonStopTrackingTouch(SeekBar
seekBar) {
intcur
= seekBar.getProgress();
Intent intent =newIntent(
Constants.CAST_ACTION_SEEKBAR_PROCESS);
intent.putExtra(Constants.INTENT_EXTRA_MUSIC_CUR_LEN,
cur);
lbManager.sendBroadcast(intent);
}
/**
*自定义广播接受者
*/
classPrgReceiverextendsBroadcastReceiver
{
@Override
public
void onReceive(Context context, Intent intent) {
//TODO接收播放服务组件中发送的进度广播
String
action = intent.getAction();
if(action.equals(Constants.CAST_ACTION_MUSIC_PROGRESS))
{
intmax
= intent.getIntExtra(
Constants.INTEXT_EXTRA_MUSIC_TOTAL_LEN,0);
intcur
= intent.getIntExtra(
Constants.INTENT_EXTRA_MUSIC_CUR_LEN,0);
seekBar.setMax(max);
seekBar.setProgress(cur);
nowTimeTv.setText(dateFormat.format(newDate(cur)));
totalTimeTv.setText(dateFormat.format(newDate(max)));
}else if(action.equals(Constants.CAST_ACTION_MUSIC_COMPLETE))
{
//接收service发的播放完成的通知
notifyPlayIb.setBackgroundResource(R.drawable.notify_play_selector);
//正常播放完成,直接跳到下一首
curPlayPosition=
intent.getIntExtra(Constants.INTENT_EXTRA_MUSIC_POSITION, -1);
//更新UI
updateOtherUI(curPlayPosition);
//播放完成,这段时间还没开始播放--
isPlaying=false;
notifyPlayIb.setEnabled(false);
updatePlayUI(isPlaying);
}else if(action.equals(Constants.CAST_ACTION_MUSIC_START)){
//TODO开始播放
// notifyPlayIb.setBackgroundResource(R.drawable.notify_pause_selector);
isPlaying=true;
notifyPlayIb.setEnabled(true);
updatePlayUI(isPlaying);
}else if(action.equals(Constants.CAST_ACTION_BUFFERING_UPDATE)){
intprogress
= intent.getIntExtra(Constants.INTENT_EXTRA_BUFFERING_UPDATE,0);
intmax
= intent.getIntExtra(Constants.INTEXT_EXTRA_MUSIC_TOTAL_LEN,0);
seekBar.setMax(max);
seekBar.setSecondaryProgress(progress);
// Log.e("--=====----==", "max:" + max + "senProgress:" + progress);
}
}
}
@Override
public
void onDestroy() {
super.onDestroy();
lbManager.unregisterReceiver(prgReceiver);
}
播放列表存放在里application中,这个地方可以优化
1
PlayService中:播放路径从intent中获取
@Override public void onCreate() { super.onCreate(); mPlayer = new MediaPlayer(); //设置播放完成的监听 mPlayer.setOnCompletionListener(PlayService.this); //设置异步准备的监听mPlayer.setOnPreparedListener(this); mPlayer.setOnBufferingUpdateListener(this);//Register a callback to be invoked when the status of a network stream's buffer has changed. // 获取本地广播管理器 lbManager = LocalBroadcastManager.getInstance(getApplicationContext()); proReceiver = new ProReceiver(); lbManager.registerReceiver(proReceiver, new IntentFilter(Constants.CAST_ACTION_SEEKBAR_PROCESS)); } @Override public int onStartCommand(Intent intent, int flags, int startId) { // 判断是否播放新的歌曲 if (intent != null) { if (intent.getBooleanExtra(Constants.INTENT_EXTRA_CHANGE_MUSIC, false)) { // 获取播放路径 String path = intent.getStringExtra(Constants.INTENT_EXTRA_MUSIC_PATH); curPosition = intent.getIntExtra(Constants.INTENT_EXTRA_MUSIC_POSITION, -1); if(curPosition > -1 && curPosition < FMApplication.INSTANCE.getPlayList().size()){ playMusic(curPosition); } }else { if (mPlayer.isPlaying()) { mPlayer.pause();// 暂停 } else { mPlayer.start();// 播放 new ProgressThread().start();//启动进度线程 } } } return super.onStartCommand(intent, flags, startId); } /** * 播放音乐 * @param position */ private void playMusic(int position){ if(position >= 0 && position < FMApplication.INSTANCE.getPlayList().size()){ String path = FMApplication.INSTANCE.getPlayList().get(position).getPlayUrl64(); //播放新歌曲 - reset mPlayer.reset(); try { mPlayer.setDataSource(path); mPlayer.prepareAsync(); } catch (Exception e) { e.printStackTrace(); } } } /** * 播放一首音乐结束的回调方法,发送播放完毕的广播 * @param mediaPlayer */ @Override public void onCompletion(MediaPlayer mediaPlayer) { if(++curPosition == FMApplication.INSTANCE.getPlayList().size()) curPosition = 0; playMusic(curPosition); // TODO 发送播放完毕的广播 Intent intent = new Intent(Constants.CAST_ACTION_MUSIC_COMPLETE); intent.putExtra(Constants.INTENT_EXTRA_MUSIC_POSITION, curPosition); lbManager.sendBroadcast(intent); } /** * 缓存数据成功回调 * @param mediaPlayer */ @Override public void onPrepared(MediaPlayer mediaPlayer) { if (mPlayer.isPlaying()) { mPlayer.pause();// 暂停 } else { mPlayer.start();// 播放 new ProgressThread().start();//启动进度线程 // TODO 发送开始播放广播给 PlayActivity Intent intent = new Intent(Constants.CAST_ACTION_MUSIC_START); lbManager.sendBroadcast(intent); } } /** * 缓存 * @param mediaPlayer * @param progress */ @Override public void onBufferingUpdate(MediaPlayer mediaPlayer, int progress) { // TODO 发送开始播放广播给 PlayActivity Intent intent = new Intent(Constants.CAST_ACTION_BUFFERING_UPDATE); sumLen = mPlayer.getDuration(); if(progress != 100){ progress = (int) (progress / 100f * sumLen); intent.putExtra(Constants.INTENT_EXTRA_BUFFERING_UPDATE, progress); intent.putExtra(Constants.INTEXT_EXTRA_MUSIC_TOTAL_LEN, sumLen);总时长 lbManager.sendBroadcast(intent); } } /** * 计算播放进度的线程 */ class ProgressThread extends Thread { @Override public void run() { try { while (mPlayer != null && mPlayer.isPlaying()) { sumLen = mPlayer.getDuration(); int currentPosition = mPlayer.getCurrentPosition(); // 准备发送进度广播 Intent intent = new Intent(Constants.CAST_ACTION_MUSIC_PROGRESS); intent.putExtra(Constants.INTEXT_EXTRA_MUSIC_TOTAL_LEN, sumLen); intent.putExtra(Constants.INTENT_EXTRA_MUSIC_CUR_LEN, currentPosition); lbManager.sendBroadcast(intent); Thread.sleep(500);//200ms发一次 ,必须大于0,否则 ANR } } catch (Exception e) { e.printStackTrace(); } } } /** * 进度广播接收者 */ class ProReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { int cur = intent.getIntExtra(Constants.INTENT_EXTRA_MUSIC_CUR_LEN, 0);//从播放界面发送过来的进度 mPlayer.seekTo(cur); } } @Override public void onDestroy() { super.onDestroy(); lbManager.unregisterReceiver(proReceiver); mPlayer.release(); } @Nullable @Override public IBinder onBind(Intent intent) { return null; }
2 activity 中
/**
*通知服务播放对应位置的音乐
*@paramposition
*/
private voidplayMusic(intposition,booleanplayNew){
Intent serviceIntent =newIntent(this,
PlayService.class);
serviceIntent.putExtra(Constants.INTENT_EXTRA_CHANGE_MUSIC,
playNew);
if(playNew){
if(position
> -1&& position < FMApplication.INSTANCE.getPlayList().size())
serviceIntent.putExtra(Constants.INTENT_EXTRA_MUSIC_POSITION,
position);
}
startService(serviceIntent);
}
caseR.id.ac_notify_play_ib:
//TODO点击播放按钮处理
isPlaying=
!isPlaying;
Log.e("--============","activity:isPlaying
: "+isPlaying);
playMusic(-1,false);
//更新playUI
updatePlayUI(isPlaying);
break;
*******************-----------*********************
caseR.id.ac_notify_pre_ib:
//TODO点击上一首按钮处理
if(--curPlayPosition==
-1)
curPlayPosition=
FMApplication.INSTANCE.getPlayList().size() -
1;
playMusic(curPlayPosition,true);
notifyPlayIb.setEnabled(false);
notifyPlayIb.setBackgroundResource(R.drawable.notify_pause_selector);
updateOtherUI(curPlayPosition);
break;
caseR.id.ac_notify_next_ib:
//TODO点击下一首按钮处理
if(++curPlayPosition==
FMApplication.INSTANCE.getPlayList().size())
curPlayPosition=0;
playMusic(curPlayPosition,true);
notifyPlayIb.setEnabled(false);
notifyPlayIb.setBackgroundResource(R.drawable.notify_pause_selector);
updateOtherUI(curPlayPosition);
break;
**********************************
//-------------------------seekBar回调方法
@Override
public voidonStopTrackingTouch(SeekBar
seekBar) {
intcur
= seekBar.getProgress();
Intent intent =newIntent(
Constants.CAST_ACTION_SEEKBAR_PROCESS);
intent.putExtra(Constants.INTENT_EXTRA_MUSIC_CUR_LEN,
cur);
lbManager.sendBroadcast(intent);
}
/**
*自定义广播接受者
*/
classPrgReceiverextendsBroadcastReceiver
{
@Override
public
void onReceive(Context context, Intent intent) {
//TODO接收播放服务组件中发送的进度广播
String
action = intent.getAction();
if(action.equals(Constants.CAST_ACTION_MUSIC_PROGRESS))
{
intmax
= intent.getIntExtra(
Constants.INTEXT_EXTRA_MUSIC_TOTAL_LEN,0);
intcur
= intent.getIntExtra(
Constants.INTENT_EXTRA_MUSIC_CUR_LEN,0);
seekBar.setMax(max);
seekBar.setProgress(cur);
nowTimeTv.setText(dateFormat.format(newDate(cur)));
totalTimeTv.setText(dateFormat.format(newDate(max)));
}else if(action.equals(Constants.CAST_ACTION_MUSIC_COMPLETE))
{
//接收service发的播放完成的通知
notifyPlayIb.setBackgroundResource(R.drawable.notify_play_selector);
//正常播放完成,直接跳到下一首
curPlayPosition=
intent.getIntExtra(Constants.INTENT_EXTRA_MUSIC_POSITION, -1);
//更新UI
updateOtherUI(curPlayPosition);
//播放完成,这段时间还没开始播放--
isPlaying=false;
notifyPlayIb.setEnabled(false);
updatePlayUI(isPlaying);
}else if(action.equals(Constants.CAST_ACTION_MUSIC_START)){
//TODO开始播放
// notifyPlayIb.setBackgroundResource(R.drawable.notify_pause_selector);
isPlaying=true;
notifyPlayIb.setEnabled(true);
updatePlayUI(isPlaying);
}else if(action.equals(Constants.CAST_ACTION_BUFFERING_UPDATE)){
intprogress
= intent.getIntExtra(Constants.INTENT_EXTRA_BUFFERING_UPDATE,0);
intmax
= intent.getIntExtra(Constants.INTEXT_EXTRA_MUSIC_TOTAL_LEN,0);
seekBar.setMax(max);
seekBar.setSecondaryProgress(progress);
// Log.e("--=====----==", "max:" + max + "senProgress:" + progress);
}
}
}
@Override
public
void onDestroy() {
super.onDestroy();
lbManager.unregisterReceiver(prgReceiver);
}
相关文章推荐
- Android启动服务播放音乐(两种启动方式)
- 音乐播放 启动方式 (2) service发送msg给activity
- 实现Activity中控制service里音乐播放、暂停的两种方式
- Android 发送多个不同的快捷方式(shortcut)到桌面并向其启动的Activity传参
- Android Service与Activity之间通信的几种方式(1)---通过broadcast(广播)的形式
- Android(java)学习笔记181:Android 服务的应用,在Activity中实现背景音乐播放
- Android Notification 使用详解之三:通过服务更新进度通知&在Activity中监听服务进度
- Android 通过广播启动另一个应用的Activity
- android 学习receiver和发送广播,其中监听其他activity的启动demo;给activity加自定义权限只有指定有权限的app可以监听到
- Android 启动Service服务和发送Broadcast广播的常用方法
- android--通过广播启动另一个应用的Activity
- Android中通过耳机按键控制音乐播放的实现
- Android笔记之高德地图定位(通过开启服务发送广播用handle消息机制更新位置信息)
- Android多媒体开发 音乐播放(加带进度条、时间显示)以及使用SoundPool播放音效
- Android窗口管理服务WindowManagerService显示Activity组件的启动窗口(Starting Window)的过程分析
- Android窗口管理服务WindowManagerService显示Activity组件的启动窗口(Starting Window)的过程分析
- Android开发——通过广播启动另一个应用的Activity
- Android窗口管理服务WindowManagerService显示Activity组件的启动窗口(Starting Window)的过程分析
- Android窗口管理服务WindowManagerService显示Activity组件的启动窗口(Starting Window)的过程分析
- 第92章、广播之三通过广播启动服务(从零开始学Android)