播放網絡資源的方式。
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Binder;
import android.os.IBinder;
import java.io.IOException;
public class MusicService extends Service {
private MediaPlayer player; //聲明一個播放器
private boolean isStop = false; //判斷 目前是否有音樂在播放
private Uri uri; // 音樂的播放位址
@Override
public IBinder onBind(Intent intent) {
// 使用綁定式服務,将音樂的位址發送到服務中。
MyBind bind = new MyBind();
String music = intent.getStringExtra("music");
uri = Uri.parse(music);
preparePlayer();
return bind;
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
if (player == null) {
player = new MediaPlayer();
// 播放完成時的監聽事件
player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mp.release();
}
});
player.setOnErrorListener(new MediaPlayer.OnErrorListener() {
// 播放失敗的監聽事件
@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
// TODO Auto-generated method stub
mp.reset();
return false;
}
});
}
}
// 準備播放
private void preparePlayer() {
player.reset();
try {
player.setDataSource(this,uri);
player.prepare();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
// 傳回服務本身。用來在Activity中使用
public class MyBind extends Binder {
public MusicService getInstance() {
return MusicService.this;
}
}
// 要進行播放的音樂的總時長
public int getDuration(){
return player.getDuration();
}
// 目前音樂播放的位置
public int getCurrent(){
if (player!=null) {
return player.getCurrentPosition();
}
return 0;
}
public void play() {
if (isStop) {
preparePlayer();
player.start();
isStop = false;
} else if (player != null && !player.isPlaying()) {
player.start();
}
}
public void pause() {
if (player != null && player.isPlaying()) {
player.pause();
}
}
public void stop() {
if (player != null) {
player.stop();
isStop = true;
player.release();
}
}
// 取消綁定
@Override
public boolean onUnbind(Intent intent) {
// TODO Auto-generated method stub
if (player != null) {
player.release();
player = null;
}
return super.onUnbind(intent);
}
}
完整的服務端代碼如上,接下來是在Activity中的代碼
// 顯示意圖,轉至服務類
intent = new Intent(MainActivity.this, MusicService.class);
// 傳值 ,将音樂播放的位址發送給服務端
intent.putExtra("music", music);
// 服務連接配接類
conn = new MyServiceConn();
// 綁定服務
bindService(intent, conn, Context.BIND_AUTO_CREATE);
public class MyServiceConn implements ServiceConnection {
// 服務連接配接的時候調用的方法
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
// 相通過Ibinder對象擷取Service對象
MusicService.MyBind service2=(MusicService.MyBind) service;
myService=service2.getInstance();
// 服務綁定成功 就可以直接進行音樂的播放操作
myService.play();
}
@Override
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub
}
}