我有一个绑定到应用程序上下文的服务,如下所示:
getApplicationContext().bindService(
new Intent(this, ServiceUI.class),
serviceConnection,
Context.BIND_AUTO_CREATE
);
protected void onDestroy() {
super.onDestroy();
getApplicationContext().unbindService(serviceConnection);
}
Run Code Online (Sandbox Code Playgroud)
出于某种原因,有时只有应用程序上下文没有正确绑定(我无法修复该部分),但是在onDestroy()中我做了unbindservice哪个会抛出错误
java.lang.IllegalArgumentException: Service not registered: tools.cdevice.Devices$mainServiceConnection.
Run Code Online (Sandbox Code Playgroud)
我的问题是:unbindservice在解除绑定之前,有没有办法安全地打电话或检查它是否已绑定到服务?
提前致谢.
And*_*kov 65
试试这个:
boolean isBound = false;
...
isBound = getApplicationContext().bindService( new Intent(getApplicationContext(), ServiceUI.class), serviceConnection, Context.BIND_AUTO_CREATE );
...
if (isBound)
getApplicationContext().unbindService(serviceConnection);
Run Code Online (Sandbox Code Playgroud)
注意:
您应该使用它context来绑定服务和解除绑定服务.如果您绑定服务,getApplicationContext()那么您也应该使用getApplicationContext.unbindService(..)
在这里,您可以找到一个很好的解释和源代码如何使用绑定服务.在您的情况下,您应该覆盖对象的方法(onServiceConnected和onServiceDisconnected)ServiceConnection.然后你可以检查mBound代码中的变量.
小智 5
完全按照安德烈·诺维科夫的建议做对我没有用。我简单地替换为:
getApplicationContext().unbindService(serviceConnection);
Run Code Online (Sandbox Code Playgroud)
带有:
unbindService(serviceConnection);
Run Code Online (Sandbox Code Playgroud)
我发现有两个问题。尝试绑定不止一次,并且尝试解除绑定不止一次。
解:
public class ServiceConnectionManager implements ServiceConnection {
private final Context context;
private final Class<? extends Service> service;
private boolean attemptingToBind = false;
private boolean bound = false;
public ServiceConnectionManager(Context context, Class<? extends Service> service) {
this.context = context;
this.service = service;
}
public void bindToService() {
if (!attemptingToBind) {
attemptingToBind = true;
context.bindService(new Intent(context, service), this, Context.BIND_AUTO_CREATE);
}
}
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
attemptingToBind = false;
bound = true;
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
bound = false;
}
public void unbindFromService() {
attemptingToBind = false;
if (bound) {
context.unbindService(this);
bound = false;
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
55811 次 |
| 最近记录: |