Why does my Android service get restarted when the process is killed, even though I used START_NOT_STICKY?

后端 未结 3 1189
忘掉有多难
忘掉有多难 2021-01-29 19:20

My app uses a pattern where I start a service with Context#startService() as well as bind to it with Context#bindService(). This is so that I can control the lifetime of the se

3条回答
  •  佛祖请我去吃肉
    2021-01-29 19:46

    How about reconsidering your pattern?

    The START_NOT_STICKY flag appeared at some point during Android evolution (after 1.6?). Most probably, you are facing some subtle regression in service life cycle, which was introduced at that time. So, even if an equally subtle solution is found for now - and magically verified to work on all possible devices - it will not necessarily work under new Android versions.

    Anyway, that life cycle pattern looks unusual, and that might be the very reason for your running into this exotic problem.

    Let's consider two cases.

    1. Normal (?). Some activity starts the service. Soon after that it gets bound, used, unbound - then what? Stopped somehow? How come there's no significant battery drain in this case?

    2. Abnormal. Service killed at some (random?) point. When restarted, it implements some wrong assumption and stays active, doing something that drains the battery?

    It all looks rather strange.

    I would analyze the concurrent processes in your product. All significant cases. Some diagrams, etc. Most probably, as a result, the very need for such a pattern would be eliminated.

    Otherwise, it looks like any workaround will be a fragile hack.

提交回复
热议问题