1、單獨(dú)使用startService & stopService
(1)第一次調(diào)用startService會執(zhí)行onCreate、onStartCommand。
(2)之后再多次調(diào)用startService只執(zhí)行onStartCommand,不再執(zhí)行onCreate。
(3)調(diào)用stopService會執(zhí)行onDestroy。
2、單獨(dú)使用bindService & unbindService
(1)第一次調(diào)用bindService會執(zhí)行onCreate、onBind。
(2)之后再多次調(diào)用bindService不會再執(zhí)行onCreate和onBind。
(3)調(diào)用unbindService會執(zhí)行onUnbind、onDestroy。
3、startService與bindService混合使用
使用場景:在activity中要得到service對象進(jìn)而能調(diào)用對象的方法,但同時又不希望activity finish的時候service也被destory了,startService和bindService混合使用就派上用場了。
(1)先調(diào)用startService,再調(diào)用bindService,生命周期如下:
startService(new Intent(this, MyService.class));
bindService(new Intent(this, MyService.class), mServiceConnection, Context.BIND_AUTO_CREATE);
onCreate-onStartCommand-onBind
(2)先調(diào)用bindService,再調(diào)用startService,生命周期如下:
bindService(new Intent(this, MyService.class), mServiceConnection, Context.BIND_AUTO_CREATE);
startService(new Intent(this, MyService.class));
onCreate-onBind-onStartCommand
(3)先調(diào)用startService又調(diào)用了bindService,他們對應(yīng)的是同一個service對象嗎?
答案是的。
論點(diǎn)1:service輸出“bindService == startService”。
論點(diǎn)2:如果不是同一個service,應(yīng)該會執(zhí)行兩次onCreate。
————————————————
原文鏈接:https://blog.csdn.net/ican87/java/article/details/82945867