目前,我需要一个绑定(bind)(音乐)服务,因为我需要与之交互。但我也希望它不会停止,即使所有组件都已解除绑定(bind)。
"[...] Multiple components can bind to the service at once, but when all of them unbind, the service is destroyed."
指南还说
"[...] your service can work both ways—it can be started (to run indefinitely) and also allow binding."
在我的应用程序中,服务在应用程序启动时启动。 我只想通过用户单击我在自定义通知中显示的关闭按钮来销毁此服务。但目前,当我销毁我的 MainActivity 时,该服务也会停止。
这是我现在所在的位置,当我想创建我的服务时调用它:
public void createServiceConnection(){
musicConnection = new ServiceConnection(){
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
MusicService.MusicBinder binder = (MusicService.MusicBinder)service;
musicSrv = binder.getService();
attachMusicService();
}
};
}
...这叫做:
public void attachMusicService(){
playerFragment.setMusicService(musicSrv);
musicSrv.attach(context); //need this for my listeners, nevermind
bindService(context);
}
...这叫做:
public void bindService(Context act){
if(playIntent==null){
playIntent = new Intent(act, MusicService.class);
act.startService(playIntent);
act.bindService(playIntent, musicConnection, Context.BIND_AUTO_CREATE);
}else{
act.startService(playIntent);
act.bindService(playIntent, musicConnection, Context.BIND_AUTO_CREATE);
}
//finished. I can do stuff with my Service here.
}
我是不是误会了什么? 我觉得服务应该继续运行,即使 Activity 被破坏,因为我首先创建了一个启动服务然后绑定(bind)到它。
最佳答案
从自定义应用程序类绑定(bind)到您的服务。我不认为在绑定(bind)到它的 Activity 被销毁后(当调用 onDestroy 时)你可以保持服务 Activity 。如果 Activity 暂停 (onPause),您可以通过从服务调用 startForeground 来保持服务 Activity
关于java - 不要在 Activity 销毁时销毁绑定(bind)服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36116948/