我有2个活动,A & B.该服务在B开始有这样的代码:如何停止Android中的其他活动的服务?
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闭合,但音乐播放)。如何从OnDestroy()调用StopService?需要我解除它,如果是的话,如何以及在哪里?
简单地把stopService(new Intent(this,PlayerService.class));
导致一个错误:活动B泄漏了服务连接...这是最初绑定在这里。 (但是,B是已经关闭)
谢谢,我会尝试 – Tramway11
startService在onCreate中绑定onStart并在onStop中解除绑定。 –
似乎是工作,如果只有多次运行B并返回到A不会导致一些问题(例如,连接没有及时进行/关闭,一些并发问题)。 – Tramway11