Android service onCreate is called multiple times

2019-01-11 08:02发布

In my app, I use a service to communicate with our server. The Service spawns several message queue threads to deal with tasks with different priorities.

This model has been used for about one year without big issues. However, recently, I found some time the onCreate of my service class are called multiple times. onDestroy is never called between two onCreate calls. Therefore, I did not get chance to kill existing threads. Once this behavior happens, the service has duplicate threads inside.

The only thing I have changed is to run the service as foreground service is a user signs in the app. I am wondering whether foreground service cause the problem.

Any ideas?

3条回答
仙女界的扛把子
2楼-- · 2019-01-11 08:13

I had exactly the same problem when I was dealing with a bluetooth service (the problem occurred during the development). When I disconnected my device and killed the ADB it didn't happen again and onCreate was called only once. I assume it is some bug because it happens from time to time. But maybe you have a slightly different problem...

查看更多
Lonely孤独者°
3楼-- · 2019-01-11 08:32

I had the same problem when my service used the same process with activities(default). but no more problems when I made my service use another process. I edited my AndroidManifest.xml like below... (added android:process attribute)

<service android:name="kr.co.pkbio.binoo.CacheFileManagerService" android:process=":kr.co.pkbio.binoo.service"/>
<service android:name="kr.co.pkbio.binoo.ActivityStackManagerService" android:process=":kr.co.pkbio.binoo.service"/>

see http://developer.android.com/guide/topics/manifest/service-element.html for information.

查看更多
在下西门庆
4楼-- · 2019-01-11 08:34

This might become useful to someone. I had this same issue when storing a map through a bundle in a onSaveInstanceState method in one of my activities. I believe because the map contained references to objects that were being used in other parts of the app (one of them was my service) every time I left said activity, my service would start all over again.

I'm guessing this is android OS shenanigans.

查看更多
登录 后发表回答