私はこのようにアプリケーションコンテキストにバインドされているサービスを持っています。
getApplicationContext().bindService(
new Intent(this, ServiceUI.class),
serviceConnection,
Context.BIND_AUTO_CREATE
);
protected void onDestroy() {
super.onDestroy();
getApplicationContext().unbindService(serviceConnection);
}
しかし、onDestroy() で unbindservice
を実行すると、次のようなエラーがスローされます。
java.lang.IllegalArgumentException: Service not registered: tools.cdevice.Devices$mainServiceConnection.
質問は、安全に unbindservice
を呼び出す方法、またはバインドを解除する前に既にサービスにバインドされているかどうかをチェックする方法はありますか?
事前にありがとうございます。
これを試してみてください。
boolean isBound = false;
...
isBound = getApplicationContext().bindService( new Intent(getApplicationContext(), ServiceUI.class), serviceConnection, Context.BIND_AUTO_CREATE );
...
if (isBound)
getApplicationContext().unbindService(serviceConnection);
注意:
サービスのバインディングとアンバインディングには、同じ context
を使用する必要があります。もし、getApplicationContext()
でサービスをバインドしているなら、getApplicationContext.unbindService(...)
も使用する必要があります。
Andrey Novikovが提案したとおりのことをしても、私にはうまくいきませんでした。 私は単に置き換えただけです。
getApplicationContext().unbindService(serviceConnection);
としました。
unbindService(serviceConnection);