Androidで独自のServiceを実装する際、bindとunbindを繰り返すような実装を行わなければならないことがある。
この時、最初のbind時にはonBind
が実行され、unbind後に再度bindするとonRebind
が実行されることを期待したコードを書くことになるが、実装方法を間違えると再bind時にonRebind
が呼ばれないという現象が発生するので注意が必要となる。
onUnbindでfalseを返すとonRebindが呼ばれない
ずばり見出しの通りだが、onUnbind
でfalseを返すようになっているServiceは、unbind後に再度bindしてもonRebind
が呼ばれない。
再bindしてるんだから勝手にonRebindしてくれよと思わないでもないが、この動作はしっかりリファレンスに記載されている。
public void onRebind (Intent intent)
Called when new clients have connected to the service, after it had previously been notified that all had disconnected in its onUnbind(Intent). This will only be called if the implementation of onUnbind(Intent) was overridden to return true.
ちなみにonUnbind
はデフォルトでは以下のようにfalseを返すのみの実装になっている。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
/** * Called when all clients have disconnected from a particular interface * published by the service. The default implementation does nothing and * returns false. * * @param intent The Intent that was used to bind to this service, * as given to {@link android.content.Context#bindService * Context.bindService}. Note that any extras that were included with * the Intent at that point will <em>not</em> be seen here. * * @return Return true if you would like to have the service's * {@link #onRebind} method later called when new clients bind to it. */ public boolean onUnbind(Intent intent) { return false; } |
つまり、カスタムのServiceを作ってonRebind
で何か処理したい場合、以下の手順が必要となる。
onRebind
を実装するonUnbind
をオーバーライドしてtrueを返す
onUnbind
で確実にtrueを返すようになっているか確認するようにしましょう。
教訓
リファレンスを見よう。ログで確認しよう。
以上。