我正在玩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;
}
}
}
当我不离开活动时,它工作正常,但是当我这样做并且音乐仍在播放时,当我返回并点击停止时,没有任何反应。当我按下播放按钮时,会启动另一个流。
调试器显示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;
}
答案 0 :(得分:3)
您是否在关闭事件处理程序(例如您的活动的onStop
)上取消绑定服务?如果是这样,该服务是未绑定和销毁的,并且您仍然听到音乐的唯一原因是因为MediaPlayer仍处于活动状态。使用绑定服务,每次绑定然后解除绑定时都会获得一个新实例。
如果您想要持久服务实例,请使用startService。服务的生命周期将独立于任何绑定活动,您可以调用stopService来结束服务实例。