AudioService
在构造函数中初始化MediaPlayer
,并将其公开给Activity
。
public class AudioService extends Service implements MediaPlayer.OnPreparedListener {
private static final String TAG = "AudioService";
MediaPlayer mMediaPlayer = new MediaPlayer();
private final IBinder mBinder = new AudioBinder();
public void onCreate () {
mMediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
mMediaPlayer.setOnPreparedListener(this);
}
/** Called when MediaPlayer is ready */
public void onPrepared(MediaPlayer player) {
player.start();
}
public AudioService() {}
public boolean initPlayer(final String section){
try {
AssetFileDescriptor afd = getAssets().openFd("records/"+section+".mp3");
mMediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
mMediaPlayer.prepareAsync();
return true;
}catch (IOException e){
e.printStackTrace();
return false;
}
}
public MediaPlayer getPlayer(){
return mMediaPlayer;
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
@Override
public void onDestroy() {
if (mMediaPlayer != null) mMediaPlayer.release();
}
public class AudioBinder extends Binder {
AudioService getService() {
return AudioService.this;
}
}
}
我不知道是否可以直接从MediaPlayer
操纵Activity
。
public class PageActivity extends FragmentActivity {
String TAG = "PageActivity";
MediaPlayer player;
Handler handler = new Handler();
Button toggle;
boolean isSeekBarDragging = false;
String section;
AudioService audioService;
public ServiceConnection myConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className, IBinder binder) {
audioService = ((AudioService.AudioBinder)binder).getService();
if(audioService.initPlayer(section)){
player = audioService.getPlayer();
}else {
seekBar.setEnabled(false);
}
}
@Override
public void onServiceDisconnected(ComponentName className) {
audioService = null;
player = null;
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page);
//bind service
bindService(new Intent(this, AudioService.class), myConnection, Context.BIND_AUTO_CREATE);
}
private void initButtons() {
toggle.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//!!! Exception is thrown here.
if(player.isPlaying()){
player.pause();
}else {
player.start();
}
}
});
}
@Override
protected void onStop(){
if(player.isPlaying()) player.stop();
handler.removeCallbacks(updater);
super.onStop();
}
}