使用MediaPlayer在Service中后台播放网络音乐

注释都在里面,大家可以看一下,里面使用了Messenger作为Service与Activity的通信

package com.ligongmusic.service;

import java.io.IOException;

import com.ligongmusic.R;
import com.ligongmusic.activity.MusicActivity;
import com.ligongmusic.util.LoggerUtils;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.os.SystemClock;
import android.view.View;
import android.widget.RemoteViews;

public class MusicOnlineService extends Service implements OnBufferingUpdateListener, OnPreparedListener, OnCompletionListener{
	private Context mContext;
	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onPrepared(MediaPlayer mp) {
		// 播放
		mp.start();
		MusicThread thread = new MusicThread();
		thread.start();
	}
	
	@Override
	public void onCompletion(MediaPlayer mp) {
		// 播放完成
		if(isLoop)//如果设置单曲循环,则跳过方法
			return;
		// 获取下一首 
		try {
			Message msg = new Message();
			msg.what = PLAYER_NEXT;
			mMessenger.send(msg);
		} catch (RemoteException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onBufferingUpdate(MediaPlayer mp, int percent) {
		// TODO Auto-generated method stub
		
	}
	private boolean isPrepare = false;
	private MediaPlayer mPlayer;
    public static final int START_MUSIC = 0;
    public static final int PAUSE_MUSIC = 1;
    public static final int CONTINUE_MUSIC = 2;
    public static final int STOP_MUSIC = 3;
    public static final int SEEK_TO_PROGRESS = 4;
    public static final int DURATION_TYPE = 5;
    public static final int CURRENT_TIME_TYPE = 6;
    public static final int PLAYER_NEXT = 7;
    public static final int SEEK_RESUME = 8;
    public static final int CHANGE_SEEK = 9;
    private boolean isLoop = false;
    private String playIng = "";// 正在播放
    private Messenger mMessenger;
	
	public int onStartCommand(Intent intent, int flags, int startId) {
		if(intent == null)
			return super.onStartCommand(intent, flags, startId);
		int status = intent.getIntExtra("status", -1);
		// 改变播放设置
		int playerSetting = intent.getIntExtra("playerSetting", -1);
		if(playerSetting == 0){
			//表示设置循环播放 
			isLoop = true;
			mPlayer.setLooping(isLoop);
		} else {
			// 设置非循环播放 
			isLoop = false;
			mPlayer.setLooping(isLoop);
		}
		switch (status) {
		case START_MUSIC:
			// 播放音乐
			playNewMusic(intent);
			break;
		case PAUSE_MUSIC:
			// 暂停
			pauseMusic(intent);
			break;
		case CONTINUE_MUSIC:
			// 继续
			restartMusic(intent);
			break;
		case STOP_MUSIC:
			// 停止
			stopMusic(intent);
			break;
		case SEEK_TO_PROGRESS:
			// 移动进度条
			playMusicByProgress(intent);
			break;
		default:
			// 第一次创建时,获取到Activity中的Messenger对象
	     	mMessenger = (Messenger) intent.getExtras().get("messenger");
	     	break;
		}
        return super.onStartCommand(intent, flags, startId);
    }
	
	@Override
	public void onCreate() {
		super.onCreate();
		// 获取上下文
		mContext = getApplicationContext();
		// 此方法只被调用一次,初始化MediaPlayer
		mPlayer = new MediaPlayer();  
        mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);// 设置媒体流类型  
        mPlayer.setOnBufferingUpdateListener(this);  
        mPlayer.setOnPreparedListener(this);  
        mPlayer.setOnCompletionListener(this);
	}
	
	 
	private void playNewMusic(Intent intent){
		String musicPath = intent.getStringExtra("musicName");
		if(mPlayer == null)
			mPlayer = new MediaPlayer();
		mPlayer.reset();
		try{
			mPlayer.setDataSource(musicPath);
			mPlayer.prepare();
			isPrepare = true;
		}catch (IOException e) {
			e.printStackTrace();
		}
    }
    
    private void pauseMusic(Intent intent){
    	if(mPlayer == null)
    		playNewMusic(intent);
    	else{
    		mPlayer.pause();
    		// 进度条时间
			MusicThread thread = new MusicThread();
			thread.start();
    	}
    }
    
    private void stopMusic(Intent intent){
    	mPlayer.stop();
    	mPlayer.release();
    	mPlayer = null;
    }
    
    private void restartMusic(Intent intent){
    	if(mPlayer == null || !isPrepare)
    		playNewMusic(intent);
    	else{
    		mPlayer.start();
    		// 进度条时间
			MusicThread thread = new MusicThread();
			thread.start();
    	}
    }
    
    private void playMusicByProgress(Intent intent){
    	if(mPlayer == null || !isPrepare){// 如果没有选择播放的音乐,通知activity改变界面
			try {
				Message msg = new Message();
				msg.what = SEEK_RESUME;
//				msg.obj = mPlayer.getCurrentPosition();// 发送当前时长
				mMessenger.send(msg);
			} catch (RemoteException e) {
				e.printStackTrace();
			}
			LoggerUtils.getLog(MusicOnlineService.class).error(isPrepare + "");
    		return;
    	}
    	LoggerUtils.getLog(MusicOnlineService.class).error(isPrepare + "");
;
    	if(mPlayer.isPlaying()){
		//将播放位置移动到进度所在位置
    		mPlayer.seekTo(intent.getIntExtra("seek_time", mPlayer.getCurrentPosition()));
    		MusicThread thread = new MusicThread();
			thread.start();
    	}else{
			try {
				Message msg = new Message();
				msg.what = CHANGE_SEEK;
				msg.arg1 = intent.getIntExtra("seek_time", mPlayer.getCurrentPosition());// 发送当前时长
//				msg.arg2 = mPlayer.getDuration();// 发送总时长
//				msg.obj = mPlayer.isPlaying();
				mMessenger.send(msg);
			} catch (RemoteException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
    	}
    	
    }
    
    class MusicThread extends Thread{
    	@Override
    	public void run() {
    		while(mPlayer.isPlaying()){
    			try {
    				Message msg = new Message();
    				msg.what = CURRENT_TIME_TYPE;
    				msg.arg1 = mPlayer.getCurrentPosition();// 发送当前时长
    				msg.arg2 = mPlayer.getDuration();// 发送总时长
    				msg.obj = mPlayer.isPlaying();// 播放状态
					mMessenger.send(msg);
					SystemClock.sleep(1000);// 一秒发送一次Handler
				} catch (RemoteException e) {
					e.printStackTrace();
				}
    		}
    	}
    }

}


你可能感兴趣的:(Android开发)