版权声明:本文为博主原创文章,未经博主允许不得转载。
使用service后台播放音乐,弹出通知
public class MainActivity extends Activity {
private MusicAdpater adapter;
private IMusicPlay mMusicPlay;
private ServiceConnection conn = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
mMusicPlay = (IMusicPlay) service;
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
initData();
startMusicPalyService();
}
private void startMusicPalyService() {
Intent service = new Intent(this, MusicPlayService.class);
// 开启服务
startService(service);
bindService(service, conn, BIND_AUTO_CREATE);
}
private void initData() {
// 获取sd卡存储状态
String State = Environment.getExternalStorageState();
if (State.equals(Environment.MEDIA_UNMOUNTED)) {
Toast.makeText(this, "外部存储不存在,请插入", 0).show();
return;
}
File storageDirectory = Environment.getExternalStorageDirectory();
File[] mMusicFiles = storageDirectory.listFiles();
if (mMusicFiles == null) {
Log.v("520it", "mMusicFilesw为空");
return;
}
ArrayList mMusicPaths = new ArrayList();
for (File file : mMusicFiles) {
if (file.getAbsolutePath().endsWith(".mp3")) {
mMusicPaths.add(file.getAbsolutePath());
}
}
adapter.setDatas(mMusicPaths);
adapter.notifyDataSetChanged();
}
/*
* 初始化布局
*/
private void initView() {
ListView mMusicList = (ListView) findViewById(R.id.musicList_lv);
adapter = new MusicAdpater();
mMusicList.setAdapter(adapter);
mMusicList.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView> parent, View view,
int position, long id) {
mMusicPlay.callPlayMusic(adapter.getDatas(),position);
}
});
}
//设置播放的模式
@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
//
switch (item.getItemId()) {
case R.id.all_paly:
//顺序播放
saveMusicMode(1);
break;
case R.id.sigle_play:
//单曲播放
saveMusicMode(2);
break;
case R.id.end:
//退出应用
//1停止播放音乐,释放资源
mMusicPlay.callStopPlay();
//关闭服务
unbindService(conn);
Intent service = new Intent(this, MusicPlayService.class);
stopService(service);
//退出activity
finish();
break;
case R.id.stop_when_over:
//播放完停止
saveMusicMode(0);
break;
}
return true;
}
public void saveMusicMode(int mode){
SharedPreferences sp = getSharedPreferences("MUSIC_UTIL",MODE_PRIVATE);
Editor edit = sp.edit();
edit.putInt("MUSIC_MODE", mode);
edit.commit();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// LayoutInflater 可以将一个布局转换成View
// MenuInflater 可以将一个菜单栏布局转换成菜单的View
getMenuInflater().inflate(R.menu.main, menu);
// true 告诉系统 菜单栏我们自己处理就可以了
return true;
}
}
*************************************************************************************************************
public class MusicAdpater extends BaseAdapter{
private ArrayList mMusicPaths;
@Override
public int getCount() {
// TODO Auto-generated method stub
return mMusicPaths==null?0:mMusicPaths.size();
}
public void setDatas(ArrayList mMusicPaths) {
//
this.mMusicPaths=mMusicPaths;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
if (convertView==null) {
convertView= View.inflate(parent.getContext(), R.layout.music_item, null);
}
TextView mMusicTv = MusicUtils.getView(convertView, R.id.music_tv);
String musicName = MusicUtils.getMusicName(mMusicPaths.get(position));
mMusicTv.setText(musicName);
return convertView;
}
@Override
public String getItem(int position) {
// TODO Auto-generated method stub
return mMusicPaths.get(position);
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public ArrayList getDatas() {
// TODO Auto-generated method stub
return mMusicPaths;
}
}
*******************************************************************************************************************
public class MusicPlayService extends Service {
private MediaPlayer mediaPlayer;
private int currentMusicImndex;
private NotificationManager mManager;
private class MusicPlayServiceAgent extends Binder implements IMusicPlay {
@Override
public void callPlayMusic(ArrayList mMusicPaths, int musicIndex) {
//
playMusic(mMusicPaths, musicIndex);
}
@Override
public void callStopPlay() {
// TODO Auto-generated method stub
stopPlay();
}
}
@Override
public IBinder onBind(Intent intent) {
//
return new MusicPlayServiceAgent();
}
public void playMusic(final ArrayList mMusicPaths,
final int musicIndex) {
currentMusicImndex = musicIndex;
String mMusicPath = mMusicPaths.get(musicIndex);
try {
if (mediaPlayer == null) {
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
// 设置监听,播放完怎么做
mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
// 判断当前 播放时什么模式
SharedPreferences sp = getSharedPreferences(
"MUSIC_UTIL", MODE_PRIVATE);
int mode = sp.getInt("MUSIC_MODE", 0);
Log.v("520it", "MUSIC_MODE" + mode);
if (mode == 0) {
// 默认就是播完停止,所以这里什么都不做
} else if (mode == 1) {
// 顺序播放
currentMusicImndex++;
if (currentMusicImndex > mMusicPaths.size() - 1) {
// 如果是播放到最后,重新开始
currentMusicImndex = 0;
}
playMusic(mMusicPaths, currentMusicImndex);
} else if (mode == 2) {
// 单曲继续播放
playMusic(mMusicPaths, currentMusicImndex);
}
}
});
}
// 在通知栏显示播放的音乐
showshowNotification(MusicUtils.getMusicName(mMusicPath));
mediaPlayer.reset();
mediaPlayer.setDataSource(mMusicPath);
mediaPlayer.prepare();
mediaPlayer.start();
} catch (Exception e) {
}
}
/*
* 弹出通知框
*/
private void showshowNotification(String musicName) {
//新建通知
Notification mNotification = new Notification(R.drawable.ic_launcher,
"酷狗音乐正在播放:"+musicName, System.currentTimeMillis());
Intent intent=new Intent(this,com.m520it.myMusicPlayer.MainActivity.class);
//PendingIntent.getActivity(context, requestCode, intent, flags)
//设置点击的意图
PendingIntent contentIntent=PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
//设置下拉通知的内容
mNotification.setLatestEventInfo(this, "酷狗音乐", musicName+"播放中...", contentIntent);
if (mManager==null) {
mManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
}
//弹出提示notify通知id-用来记录到底是哪个提示信息
mManager.notify(0, mNotification);
}
public void stopPlay() {
if (mediaPlayer!=null) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
//释放志愿
mediaPlayer.release();
mediaPlayer=null;
}
if (mManager!=null) {
//关闭本应用的 所有通知
mManager.cancelAll();
}
}
}
********************************************************************************************************************************
public interface IMusicPlay {
public void callPlayMusic(final ArrayList mMusicPaths,
final int musicIndex);
public void callStopPlay();
}
**************************************************************************************************
public class MusicUtils {
//adapter获取缓存View
public static T getView(View view, int id) {
SparseArray viewHolder = (SparseArray) view.getTag();
if (viewHolder == null) {
viewHolder = new SparseArray();
view.setTag(viewHolder);
}
View childView = viewHolder.get(id);
if (childView == null) {
childView = view.findViewById(id);
viewHolder.put(id, childView);
}
return (T) childView;
}
public static String getMusicName(String path) {
return path.substring(path.lastIndexOf("/")+1);
}
}
**************************************************************
权限