文章原创,转载请注明出处:http://blog.csdn.net/feifei454498130/article/details/9306631
设计如下:
Service的代码如下,通过Binder去控制播放。监听来电没写,在Service里监听就行了。
public class MediaService extends Service {
static final int PLAY_LIST[] = {
R.raw.bigben
};
private MediaPlayer mediaPlayer;
private HashSet<OnMediaChangeListener> listeners;
private MediaBinder mBinder;
@Override
public void onCreate() {
super.onCreate();
listeners = new HashSet<OnMediaChangeListener>();
mBinder = new MediaBinder();
}
@Override
public void onDestroy() {
super.onDestroy();
listeners.clear();
try {
mediaPlayer.stop();
} catch(Exception e) {
e.printStackTrace();
}
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if(intent != null && intent.getAction() != null) {
Intent i = new Intent(intent.getAction());
sendBroadcast(i);
}
return super.onStartCommand(intent, flags, startId);
}
private void notifyAllPlay() {
Iterator<OnMediaChangeListener> iterator = listeners.iterator();
while(iterator.hasNext()) {
iterator.next().onMediaPlay();
}
}
private void notifyAllPause() {
Iterator<OnMediaChangeListener> iterator = listeners.iterator();
while(iterator.hasNext()) {
iterator.next().onMediaPause();
}
}
private void notifyAllStop() {
Iterator<OnMediaChangeListener> iterator = listeners.iterator();
while(iterator.hasNext()) {
iterator.next().onMediaStop();
}
}
private void notifyAllCompletion() {
Iterator<OnMediaChangeListener> iterator = listeners.iterator();
while(iterator.hasNext()) {
iterator.next().onMediaCompletion();
}
}
MediaPlayer.OnCompletionListener mOnCompletionListener = new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
notifyAllCompletion();
}
};
public class MediaBinder extends Binder {
public void addOnMediaChangeListener(OnMediaChangeListener listener) {
if(listener != null) {
listeners.add(listener);
}
}
public void removeOnMediaChangeListener (OnMediaChangeListener listener) {
if(listener != null) {
listeners.remove(listener);
}
}
public void play() {
if(mediaPlayer == null) {
mediaPlayer = MediaPlayer.create(MediaService.this, PLAY_LIST[0]);
mediaPlayer.setOnCompletionListener(mOnCompletionListener);
}
mediaPlayer.start();
notifyAllPlay();
}
public void pause() {
if(mediaPlayer != null) {
mediaPlayer.pause();
}
notifyAllPause();
}
public void stop() {
if(mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer = null;
}
notifyAllStop();
}
public boolean isPlaying() {
if(mediaPlayer != null) {
return mediaPlayer.isPlaying();
}
return false;
}
public int getDuration() {
if(mediaPlayer != null) {
return mediaPlayer.getDuration();
}
return -1;
}
public int getCurrentPosition() {
if(mediaPlayer != null) {
return mediaPlayer.getCurrentPosition();
}
return -1;
}
public void seek(int sec) {
if(mediaPlayer != null) {
try {
mediaPlayer.seekTo(sec);
} catch(Exception e) {
e.printStackTrace();
}
}
}
}
}
源码下载地址:http://download.csdn.net/detail/feifei454498130/5740835