我在Service
中有BroadcastReceiver
。当广播接收机在服务中注册时无法停止服务
我注册服务的oncreate()
方法类似接收器,
final MyReceiver myReceiver = new MyReceiver();
@Override
public void onCreate() {
IntentFilter filter = new IntentFilter(SOME_FILTER);
registerReceiver(myReceiver, filter);
}
然后我创建注销接收器和停止服务等的方法,
public void stopService(){
if(myReceiver != null){
try{
unregisterReceiver(myReceiver);
}catch(Exception e){
e.printStackTrace();
}
}
stopSelf();
}
但不会停止的服务。有也不例外,没有错误。只是服务不会停止。
我也试了一下下面的方式,
public void stopService(){
if(myReceiver != null){
try{
unregisterReceiver(myReceiver);
}catch(Exception e){
e.printStackTrace();
}
}
stopForeground(true);
stopSelf();
}
通过这种服务的通知被在前台运行皮,但服务的onDestroy()
不会被调用。
我也试图把代码注销接收机
onDestroy()
但调用stopSelf()
方法onDestroy()
永远不会被调用后。
如果我没有在注册该服务的BroadcastReceiver
,一切工作完全正常,服务站和onDestroy()
被调用,但是当我注册receiver
那么它不会停止。
任何想法这里发生了什么?
编辑
这是怎么了绑定和启动服务
Intent serviceIntent = new Intent(MainActivity.this, MyService.class);
bindService(serviceIntent, mConnection, Context.BIND_AUTO_CREATE);
startService(serviceIntent);
这是mConnection
MyService myService;
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className, IBinder service){
LocalBinder binder = (LocalBinder) service;
myService = binder.getService();
isBound = true;
}
@Override
public void onServiceDisconnected(ComponentName arg0) {
isBound = false;
}
};
下面是我是怎么解除绑定服务,并停止它。
if(isBound){
unbindService(mConnection);
isBound = false;
}
myService.stopService();
myService = null;
如何启动'Service'并在哪里调用'stopService()'(btw不是一个好名字,因为'ContextWrapper'中有一个类似于不同参数的方法)。另外,你是否在任何地方绑定了“服务”? –
@ci_我已将代码添加到问题中。 – gprathour
你正在提供不完整的代码,什么是playerService?你为什么不发布一个工作的客户和服务代码? – pskink