我正在玩弄MediaPlayer
. 我希望在用户离开活动时播放音乐。但是,当我离开并返回活动时,看起来我没有绑定到同一个实例。
这是我的代码:
public class MusicService extends Service {
private NotificationManager mNM;
public class LocalBinder extends Binder {
MusicService getService() {
return MusicService.this;
}
}
@Override
public void onCreate() {
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
@Override
public void onDestroy() {
// Cancel the persistent notification.
// Tell the user we stopped.
Toast.makeText(this, "destroyed", Toast.LENGTH_SHORT).show();
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
// This is the object that receives interactions from clients. See
// RemoteService for a more complete example.
private final IBinder mBinder = new LocalBinder();
public void showtoast(int i){
Toast.makeText(this, "showtoast"+i, Toast.LENGTH_SHORT).show();
}
//Music player functions
String path = "http://mp3stream";
MediaPlayer mp;
Boolean mpLoaded=false;
public void play(){
if(!mpLoaded){
try {
mp=new MediaPlayer();
mp.setDataSource(path);
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.prepareAsync();
mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
mpLoaded=true;
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void pause(){
if(mpLoaded){
mp.stop();
mpLoaded=false;
}
}
}
当我不离开活动时它工作得很好,但是当我离开并且音乐仍在播放时,当我返回并单击stop时,什么也没有发生。当我按下播放按钮时,另一个流开始了。
调试器显示这mpLoaded
是错误的,即使我可以听到服务。
这就是我绑定它的方式。
private MusicService mBoundService;
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
mBoundService = ((MusicService.LocalBinder)service).getService();
mIsBound=true;
Toast.makeText(Main.this, "service connected", Toast.LENGTH_SHORT).show();
}
public void onServiceDisconnected(ComponentName className) {
mBoundService = null;
Toast.makeText(Main.this, "service disconnected", Toast.LENGTH_SHORT).show();
}
};
void doBindService() {
bindService(new Intent(getApplicationContext(), MusicService.class), mConnection, Context.BIND_AUTO_CREATE);
mIsBound = true;
}