Dom*_*ayr 5 java service android android-activity
目前,我需要一个绑定(音乐)服务,因为我需要与它进行交互.但是我也希望它不会停止,即使所有组件都没有自行绑定.
正如Android开发者指南所说
"[...]多个组件可以同时绑定到服务,但是当所有组件解除绑定时,服务就会被破坏."
该指南还说
"[...]您的服务可以双向工作 - 它可以启动(无限期运行)并允许绑定."
在我的应用程序中,服务在应用程序启动时启动.我想只通过用户点击我在自定义通知中显示的关闭按钮来销毁此服务.但是目前,当我破坏我的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();
}
};
}
Run Code Online (Sandbox Code Playgroud)
......这称之为:
public void attachMusicService(){
playerFragment.setMusicService(musicSrv);
musicSrv.attach(context); //need this for my listeners, nevermind
bindService(context);
}
Run Code Online (Sandbox Code Playgroud)
......这称之为:
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.
}
Run Code Online (Sandbox Code Playgroud)
我误解了什么吗?我觉得服务应该继续运行,即使活动被破坏,因为我首先启动了一个启动服务然后绑定它.
看来代码是正确的。
根据这个问题,我发现我的问题是我显示的通知,这非常有趣。
似乎为无限期运行而创建的服务需要有一个通过显示的通知 startForeground(NOTIFY_ID, notification);。
我notificationmanager.notify(NOTIFY_ID, notification);之前展示了我的通知,现在我展示了
`notificationmanager.notify(NOTIFY_ID, notification);
startForeground(NOTIFY_ID, notification);`
Run Code Online (Sandbox Code Playgroud)
在我所有绑定的活动都被销毁后,服务将不再停止。