}
switch (repeatState) {
case isCurrentRepeat: // 单曲循环
repeatBtn
.setBackgroundResource(R.drawable.repeat_current_selector);
Toast.makeText(HomeActivity.this, R.string.repeat_current,
Toast.LENGTH_SHORT).show();
break;
case isAllRepeat: // 全部循环
repeatBtn
.setBackgroundResource(R.drawable.repeat_all_selector);
Toast.makeText(HomeActivity.this, R.string.repeat_all,
Toast.LENGTH_SHORT).show();
break;
case isNoneRepeat: // 无重复
repeatBtn
.setBackgroundResource(R.drawable.repeat_none_selector);
Toast.makeText(HomeActivity.this, R.string.repeat_none,
Toast.LENGTH_SHORT).show();
break;
}
break;
case R.id.play_music: // 播放音乐
if(isFirstTime) {
play();
isFirstTime = false;
isPlaying = true;
isPause = false;
} else {
if (isPlaying) {
playBtn.setBackgroundResource(R.drawable.pause_selector);
intent.setAction(“com.wwj.media.MUSIC_SERVICE”);
intent.putExtra(“MSG”, AppConstant.PlayerMsg.PAUSE_MSG);
startService(intent);
isPlaying = false;
isPause = true;
} else if (isPause) {
playBtn.setBackgroundResource(R.drawable.play_selector);
intent.setAction(“com.wwj.media.MUSIC_SERVICE”);
intent.putExtra(“MSG”, AppConstant.PlayerMsg.CONTINUE_MSG);
startService(intent);
isPause = false;
isPlaying = true;
}
}
break;
case R.id.shuffle_music: // 随机播放
if (isNoneShuffle) {
shuffleBtn
.setBackgroundResource(R.drawable.shuffle_selector);
Toast.makeText(HomeActivity.this, R.string.shuffle,
Toast.LENGTH_SHORT).show();
isNoneShuffle = false;
isShuffle = true;
shuffleMusic();
repeatBtn.setClickable(false);
} else if (isShuffle) {
shuffleBtn
.setBackgroundResource(R.drawable.shuffle_none_selector);
Toast.makeText(HomeActivity.this, R.string.shuffle_none,
Toast.LENGTH_SHORT).show();
isShuffle = false;
isNoneShuffle = true;
repeatBtn.setClickable(true);
}
break;
case R.id.next_music: // 下一首
playBtn.setBackgroundResource(R.drawable.play_selector);
isFirstTime = false;
isPlaying = true;
isPause = false;
next();
break;
case R.id.playing: //正在播放
Mp3Info mp3Info = mp3Infos.get(listPosition);
Intent intent = new Intent(HomeActivity.this, PlayerActivity.class);
intent.putExtra(“title”, mp3Info.getTitle());
intent.putExtra(“url”, mp3Info.getUrl());
intent.putExtra(“artist”, mp3Info.getArtist());
intent.putExtra(“listPosition”, listPosition);
intent.putExtra(“currentTime”, currentTime);
intent.putExtra(“duration”, duration);
intent.putExtra(“MSG”, AppConstant.PlayerMsg.PLAYING_MSG);
startActivity(intent);
break;
}
}
}
private class MusicListItemClickListener implements OnItemClickListener {
/**
*/
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
listPosition = position;
playMusic(listPosition);
}
}
public class MusicListItemContextMenuListener implements OnCreateContextMenuListener {
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
Vibrator vibrator = (Vibrator) getSystemService(Service.VIBRATOR_SERVICE);
vibrator.vibrate(50); //长按振动
musicListItemDialog(); //长按后弹出的对话框
}
}
/**
填充列表
@param mp3Infos
*/
public void setListAdpter(List<HashMap<String, String>> mp3list) {
mAdapter = new SimpleAdapter(this, mp3list,
R.layout.music_list_item_layout, new String[] { “title”,
“Artist”, “duration” }, new int[] { R.id.music_title,
R.id.music_Artist, R.id.music_duration });
mMusiclist.setAdapter(mAdapter);
}
/**
*/
public void next() {
listPosition = listPosition + 1;
if(listPosition <= mp3Infos.size() - 1) {
Mp3Info mp3Info = mp3Infos.get(listPosition);
musicTitle.setText(mp3Info.getTitle());
Intent intent = new Intent();
intent.setAction(“com.wwj.media.MUSIC_SERVICE”);
intent.putExtra(“listPosition”, listPosition);
intent.putExtra(“url”, mp3Info.getUrl());
intent.putExtra(“MSG”, AppConstant.PlayerMsg.NEXT_MSG);
startService(intent);
} else {
Toast.makeText(HomeActivity.this, “没有下一首了”, Toast.LENGTH_SHORT).show();
}
}
/**
*/
public void previous() {
listPosition = listPosition - 1;
if(listPosition >= 0) {
Mp3Info mp3Info = mp3Infos.get(listPosition);
musicTitle.setText(mp3Info.getTitle());
Intent intent = new Intent();
intent.setAction(“com.wwj.media.MUSIC_SERVICE”);
intent.putExtra(“listPosition”, listPosition);
intent.putExtra(“url”, mp3Info.getUrl());
intent.putExtra(“MSG”, AppConstant.PlayerMsg.PRIVIOUS_MSG);
startService(intent);
}else {
Toast.makeText(HomeActivity.this, “没有上一首了”, Toast.LENGTH_SHORT).show();
}
}
public void play() {
playBtn.setBackgroundResource(R.drawable.play_selector);
Mp3Info mp3Info = mp3Infos.get(listPosition);
musicTitle.setText(mp3Info.getTitle());
Intent intent = new Intent();
intent.setAction(“com.wwj.media.MUSIC_SERVICE”);
intent.putExtra(“listPosition”, 0);
intent.putExtra(“url”, mp3Info.getUrl());
intent.putExtra(“MSG”, AppConstant.PlayerMsg.PLAY_MSG);
startService(intent);
}
/**
*/
public void repeat_one() {
Intent intent = new Intent(CTL_ACTION);
intent.putExtra(“control”, 1);
sendBroadcast(intent);
}
/**
*/
public void repeat_all() {
Intent intent = new Intent(CTL_ACTION);
intent.putExtra(“control”, 2);
sendBroadcast(intent);
}
/**
*/
public void repeat_none() {
Intent intent = new Intent(CTL_ACTION);
intent.putExtra(“control”, 3);
sendBroadcast(intent);
}
/**
*/
public void shuffleMusic() {
Intent intent = new Intent(CTL_ACTION);
intent.putExtra(“control”, 4);
sendBroadcast(intent);
}
public void musicListItemDialog() {
String[] menuItems = new String[]{“播放音乐”,“设为铃声”,“查看详情”};
ListView menuList = new ListView(HomeActivity.this);
menuList.setCacheColorHint(Color.TRANSPARENT);
menuList.setDividerHeight(1);
menuList.setAdapter(new ArrayAdapter(HomeActivity.this, R.layout.context_dialog_layout, R.id.dialogText, menuItems));
menuList.setLayoutParams(new LayoutParams(ConstantUtil.getScreen(HomeActivity.this)[0] / 2, LayoutParams.WRAP_CONTENT));
final CustomDialog customDialog = new CustomDialog.Builder(HomeActivity.this).setTitle(R.string.operation).setView(menuList).create();
customDialog.show();
menuList.setOnItemClickListener( new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
customDialog.cancel();
customDialog.dismiss();
}
});
}
public void playMusic(int listPosition) {
if (mp3Infos != null) {
Mp3Info mp3Info = mp3Infos.get(listPosition);
musicTitle.setText(mp3Info.getTitle());
Intent intent = new Intent(HomeActivity.this, PlayerActivity.class);
intent.putExtra(“title”, mp3Info.getTitle());
intent.putExtra(“url”, mp3Info.getUrl());
intent.putExtra(“artist”, mp3Info.getArtist());
intent.putExtra(“listPosition”, listPosition);
intent.putExtra(“currentTime”, currentTime);
intent.putExtra(“repeatState”, repeatState);
intent.putExtra(“shuffleState”, isShuffle);
intent.putExtra(“MSG”, AppConstant.PlayerMsg.PLAY_MSG);
startActivity(intent);
}
}
@Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
/**
*/
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK
&& event.getAction() == KeyEvent.ACTION_DOWN) {
new AlertDialog.Builder(this)
.setIcon(R.drawable.ic_launcher)
.setTitle(“退出”)
.setMessage(“您确定要退出?”)
.setNegativeButton(“取消”, null)
.setPositiveButton(“确定”,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
finish();
Intent intent = new Intent(
HomeActivity.this,
PlayerService.class);
unregisterReceiver(homeReceiver);
stopService(intent); // 停止后台服务
}
}).show();
}
return super.onKeyDown(keyCode, event);
}
//自定义的BroadcastReceiver,负责监听从Service传回来的广播
public class HomeReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(action.equals(MUSIC_CURRENT)){
//currentTime代表当前播放的时间
currentTime = intent.getIntExtra(“currentTime”, -1);
musicDuration.setText(MediaUtil.formatTime(currentTime));
} else if (action.equals(MUSIC_DURATION)) {
duration = intent.getIntExtra(“duration”, -1);
}
else if(action.equals(UPDATE_ACTION)) {
//获取Intent中的current消息,current代表当前正在播放的歌曲
listPosition = intent.getIntExtra(“current”, -1);
if(listPosition >= 0) {
musicTitle.setText(mp3Infos.get(listPosition).getTitle());
}
}else if(action.equals(REPEAT_ACTION)) {
repeatState = intent.getIntExtra(“repeatState”, -1);
switch (repeatState) {
case isCurrentRepeat: // 单曲循环
repeatBtn
.setBackgroundResource(R.drawable.repeat_current_selector);
shuffleBtn.setClickable(false);
break;
case isAllRepeat: // 全部循环
repeatBtn
.setBackgroundResource(R.drawable.repeat_all_selector);
shuffleBtn.setClickable(false);
break;
case isNoneRepeat: // 无重复
repeatBtn
.setBackgroundResource(R.drawable.repeat_none_selector);
shuffleBtn.setClickable(true);
break;
}
}
else if(action.equals(SHUFFLE_ACTION)) {
isShuffle = intent.getBooleanExtra(“shuffleState”, false);
if(isShuffle) {
isNoneShuffle = false;
shuffleBtn.setBackgroundResource(R.drawable.shuffle_selector);
repeatBtn.setClickable(false);
} else {
isNoneShuffle = true;
shuffleBtn.setBackgroundResource(R.drawable.shuffle_none_selector);
repeatBtn.setClickable(true);
}
}
}
}
}
到这里,要开讲啦。
以下是需要注意的几点:
1. 音乐是通过Service来播放的,Activity通过启动服务来实现在后台播放音乐。
2. Activity中自定义了一个广播接收器,需要进行intent过滤器的定义,动作的添加,注册广播接收器:
homeReceiver = new HomeReceiver();
// 创建IntentFilter
IntentFilter filter = new IntentFilter();
// 指定BroadcastReceiver监听的Action
filter.addAction(UPDATE_ACTION);
filter.addAction(MUSIC_CURRENT);
filter.addAction(MUSIC_DURATION);
filter.addAction(REPEAT_ACTION);
filter.addAction(SHUFFLE_ACTION);
// 注册BroadcastReceiver
registerReceiver(homeReceiver, filter);
3. 在广播接收器类当中对动作进行处理,比如实现时间的更新和标题的更新等。
4. 这里还要注意按钮触发,播放状态的改变,比如音乐循环,有三种状态:单曲、全部循环、顺序,每切换一个状态都要向服务发送一条广播,通知它要改变状态。
5. 点击列表的时候,会跳入到播放界面的Activity中,要注意用intent来传递参数,注意每个参数的用途,比如title、url、MSG,就分别代表标题、路径、播放状态。
6. 长按列表会弹出自定义对话框,也会有短暂的震动效果,自定义对话框需要自行实现。这里我也贴一下实现代码吧。
package com.wwj.sb.utils;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.wwj.sb.activity.R;
/**
自定义对话框类
@author wwj
*/
public class CustomDialog extends Dialog {
public CustomDialog(Context context) {
super(context);
}
public CustomDialog(Context context, int theme) {
super(context, theme);
}
public static class Builder {
private Context context;
private int mIcon = -1; // 提示图标
private CharSequence mTitle; // 提示标题
private CharSequence mMessage; // 提示内容
private CharSequence mPositiveButtonText; // 确定按钮文本
private CharSequence mNegativeButtonText; // 取消按钮文本
private CharSequence mNeutralButtonText; // 中间按钮文本
private boolean mCancelable = true; // 是否启用取消键
private int mViewSpacingLeft;
private int mViewSpacingTop;
private int mViewSpacingRight;
private int mViewSpacingBottom;
private boolean mViewSpacingSpecified = false;
// 提示内容View
private View mView;
// 各种触发事件
private OnClickListener mPositiveButtonClickListener,
mNegativeButtonClickListener, mNeutralButtonClickListener;
private OnCancelListener mCancelListener; // 取消键事件
private OnKeyListener mKeyListener; // 按键处理
public Builder(Context context) {
this.context = context;
}
public Builder setMessage(CharSequence message) {
this.mMessage = message;
return this;
}
public Builder setMessage(int message) {
this.mMessage = context.getText(message);
return this;
}
public Builder setTitle(int title) {
this.mTitle = context.getText(title);
return this;
}
public Builder setTitle(CharSequence title) {
this.mTitle = title;
return this;
}
public Builder setIcon(int icon) {
this.mIcon = icon;
return this;
}
public Builder setView(View view) {
this.mView = view;
mViewSpacingSpecified = false;
return this;
}
public Builder setView(View view, int left, int top, int right,
int bottom) {
this.mView = view;
this.mViewSpacingLeft = left;
this.mViewSpacingTop = top;
this.mViewSpacingRight = right;
this.mViewSpacingBottom = bottom;
mViewSpacingSpecified = true;
return this;
}
public Builder setPositonButton(int textId,
final OnClickListener listener) {
this.mPositiveButtonText = context.getText(textId);
this.mPositiveButtonClickListener = listener;
return this;
}
public Builder setPostionButton(String text,
final OnClickListener listener) {
this.mPositiveButtonText = text;
this.mPositiveButtonClickListener = listener;
return this;
}
public Builder setNeutralButton(int textId,
final OnClickListener listener) {
this.mNeutralButtonText = context.getText(textId);
this.mNeutralButtonClickListener = listener;
return this;
}
public Builder setNeutralButton(String text, final OnClickListener listener) {
this.mNeutralButtonText = text;
this.mNeutralButtonClickListener = listener;
return this;
}
public Builder setNegativeButton(int textId,
final OnClickListener listener) {
this.mNegativeButtonText = context.getText(textId);
this.mNegativeButtonClickListener = listener;
return this;
}
public Builder setNegativeButton(String text,
final OnClickListener listener) {
this.mNegativeButtonText = text;
this.mNegativeButtonClickListener = listener;
return this;
}
public Builder setCancelable(boolean cancelable) {
this.mCancelable = cancelable;
return this;
}
public Builder setOnCancelListener(OnCancelListener listener) {
this.mCancelListener = listener;
return this;
}
public Builder setOnKeyListener(OnKeyListener listener) {
this.mKeyListener = listener;
return this;
}
public CustomDialog create() {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final CustomDialog dialog = new CustomDialog(context, R.style.CustomDialog);
dialog.setCancelable(mCancelable);
//设置取消键事件
if(mCancelListener != null) {
dialog.setOnCancelListener(mCancelListener);
}
//设置键盘监听事件
if(mKeyListener != null) {
dialog.setOnKeyListener(mKeyListener);
}
//获取对话框布局
View layout = inflater.inflate(R.layout.alert_dialog, (ViewGroup)(((Activity)context).findViewById(R.id.parentPanel)));
layout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
//设置标题
((TextView) layout.findViewById(R.id.alertTitle)).setText(mTitle
《Android学习笔记总结+最新移动架构视频+大厂安卓面试真题+项目实战源码讲义》
【docs.qq.com/doc/DSkNLaERkbnFoS0ZF】 完整内容开源分享
);
//设置图标
if(mIcon != -1) {
((ImageView) layout.findViewById(R.id.icon))
.setBackgroundResource(mIcon);
}
int count = 0;
//设置确定按钮
if(setButton(layout, mPositiveButtonText, R.id.button1, dialog, mPositiveButtonClickListener)) count++;