Service基础startService、bindServic

2020-06-15  本文已影响0人  霍霍9527

1、单独使用startService & stopService

(1)第一次调用startService会执行onCreate、onStartCommand。
(2)之后再多次调用startService只执行onStartCommand,不再执行onCreate。
(3)调用stopService会执行onDestroy。

2、单独使用bindService & unbindService

(1)第一次调用bindService会执行onCreate、onBind。
(2)之后再多次调用bindService不会再执行onCreate和onBind。
(3)调用unbindService会执行onUnbind、onDestroy。

3、startService与bindService混合使用

使用场景:在activity中要得到service对象进而能调用对象的方法,但同时又不希望activity finish的时候service也被destory了,startService和bindService混合使用就派上用场了。
(1)先调用startService,再调用bindService,生命周期如下:
startService(new Intent(this, MyService.class));
bindService(new Intent(this, MyService.class), mServiceConnection, Context.BIND_AUTO_CREATE);
onCreate-onStartCommand-onBind
(2)先调用bindService,再调用startService,生命周期如下:
bindService(new Intent(this, MyService.class), mServiceConnection, Context.BIND_AUTO_CREATE);
startService(new Intent(this, MyService.class));
onCreate-onBind-onStartCommand
(3)先调用startService又调用了bindService,他们对应的是同一个service对象吗?
答案是的。
论点1:service输出“bindService == startService”。
论点2:如果不是同一个service,应该会执行两次onCreate。
————————————————
原文链接:https://blog.csdn.net/ican87/java/article/details/82945867

上一篇下一篇

猜你喜欢

热点阅读