package com.example.media4;
import java.util.List;
import java.util.Map;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.widget.Button;
import android.widget.SeekBar;
public class MusicService extends Service {
private SeekBar seekBar = null;
private MediaPlayer player;
private String path = null;
private List<Map<String, Object>> musicList;
private int currentMusic = 0;
// -----进度条更新线程-------
private Thread t = new Thread() {
public void run() {
seekBar.setProgress(player.getCurrentPosition());
h.postDelayed(t, 100);
System.out.println("进度条 正在运行================");
}
};
private Handler h = new Handler() {
public void handleMessage(android.os.Message msg) {
System.out.println("HANDLER正在运行================");
}
};
// ==============获取musicList===================
public void setMusicList(List<Map<String, Object>> musicList) {
this.musicList = musicList;
}
// ======================获取SeekBar对象======================
public void setSeekBar(SeekBar seekBar) {
this.seekBar = seekBar;
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
// ===========创建播放器===========
player = new MediaPlayer();
// 异步加载资源 ====================准备资源完毕 监听
player.setOnPreparedListener(new OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
// TODO Auto-generated method stub
seekBar.setMax(player.getDuration());
player.start();
h.post(t);
}
});
super.onCreate();
}
public void play() {
if (path != null) {
player.start();
h.post(t);
System.out.println("path=" + path);
} else {
path = (String) musicList.get(currentMusic).get("filePath");
try {
player.setDataSource(path);
player.prepareAsync();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void pause() {
// TODO Auto-generated method stub
if (path != null) {// 在这里 PATH借用来 当做 初始化的标志
if (player.isPlaying()) {
player.pause();
h.removeCallbacks(t);
} else {
player.start();
h.post(t);
}
}
}
public void stop() {
// TODO Auto-generated method stub
if (path != null) {// 在这里 PATH借用来 当做 初始化的标志
player.reset();
h.removeCallbacks(t);
seekBar.setProgress(0);
path = null;
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
@Override
public boolean onUnbind(Intent intent) {
// TODO Auto-generated method stub
return super.onUnbind(intent);
}
@Override
public void onRebind(Intent intent) {
// TODO Auto-generated method stub
super.onRebind(intent);
}
public class MyBinder extends Binder {
public MusicService getService() {
return MusicService.this;
}
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return new MyBinder();
}
}