我创建的音乐播放器服务在后退时自动停止。我想连续设置它,直到歌曲可用或用户手动关闭通知窗口。任何帮助表示赞赏。
下面我放了一些我从参考文献中创建的代码
private MediaPlayer player;
private final IBinder musicBind = new MusicBinder();
public void onCreate(){
super.onCreate();
player = new MediaPlayer();
initMusicPlayer();
}
public void initMusicPlayer(){
//set player properties
player.setWakeMode(getApplicationContext(),
PowerManager.PARTIAL_WAKE_LOCK);
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
//set listeners
player.setOnPreparedListener(this);
player.setOnCompletionListener(this);
player.setOnErrorListener(this);
}
public class MusicBinder extends Binder {
MusicService getService() {
return MusicService.this;
}
}
//activity will bind to service
@Override
public IBinder onBind(Intent intent) {
return musicBind;
}
//release resources when unbind
@Override
public boolean onUnbind(Intent intent){
//player.stop();
//player.release();
return false;
}
@Override
public void onDestroy() {
//stopForeground(true);
}
此代码用于绑定服务的活动 bindService(playIntent,musicConnection,Context.BIND_AUTO_CREATE); startService(playIntent);
从上面的代码开始,我的服务已启动,但我无法直接播放歌曲,我不得不点击播放按钮
public void playSong() {
player.reset();
try {
sendName_image();
player.setDataSource(URI object);
player.prepareAsync();
} catch (Exception e) {
}
}
按下按钮
调用上面的方法答案 0 :(得分:1)
你应该打电话给player.start();
以便在玩家准备好之后开始玩