Use 0 or BIND_AUTO_CREATE for bindService's flag

前端 未结 2 727
再見小時候
再見小時候 2021-02-18 18:15

By referring to bindService (Intent service, ServiceConnection conn, int flags)

May I know, when should we use 0 for flags, and when should we should we use

2条回答
  •  难免孤独
    2021-02-18 19:11

    Semantically, use BIND_AUTO_CREATE if you're binding to a service whose lifetime is only valid for as long as it has clients bound to it. That's because the minute all clients have unbound from it, it will go down.

    Do not use BIND_AUTO_CREATE - or perhaps I should rephrase: there's no point in using BIND_AUTO_CREATE, if you're really just temporarily binding to a service in order to query or control it, and it is reasonable that this service would live on after you're done. For those cases, binding is for establishing a connection, and the service' lifecycle should be managed using startService() and stopService() (or stopSelf() in some cases).

    A commonly mentioned example of the latter case is clearly described by Google in the docs on bound services:

    "... For example, a music player might find it useful to allow its service to run indefinitely and also provide binding. This way, an activity can start the service to play some music and the music continues to play even if the user leaves the application. Then, when the user returns to the application, the activity can bind to the service to regain control of playback."

    Overall, I would say that the usage of the flag really distinguishes two very different types of use cases, rather than fine-tuned versions of the same thing.

提交回复
热议问题