我有 2 个活动,A 和 B。服务从 B 开始,代码如下:
startService(new Intent(this, PlayerService.class));
Intent connectionIntent = new Intent(this, PlayerService.class);
bindService(connectionIntent, mp3PlayerServiceConnection, Context.BIND_AUTO_CREATE);
private ServiceConnection mp3PlayerServiceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName arg0, IBinder binder) {
mp3Service = ((LocalBinder) binder).getService();
Thread t = new Thread() {
public void run() {
mp3Service.playSong(getApplicationContext(),url);
}
};
t.start();
}
@Override
public void onServiceDisconnected(ComponentName arg0) {
}
};
当我进行活动 A(B 已关闭,但播放音乐)时,我需要有可能关闭服务。如何从 A onDestroy() 调用 StopService?需要我解除绑定,如果是,如何以及在哪里?
简单地说会stopService(new Intent(this,PlayerService.class));
导致一个错误:Activity B has leaked Service connection ... 最初绑定在这里。(但 B 已经关闭)