Activity 之 Service startService()
和bindService()
的区别startService()
1 <service android:name =".MyService" />
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 public class MyService extends Service { @Nullable @Override public IBinder onBind (Intent intent) { return null ; } @Override public void onCreate () { super .onCreate(); } @Override public int onStartCommand (Intent intent, int flags, int startId) { return super .onStartCommand(intent, flags, startId); } @Override public void onDestroy () { super .onDestroy(); } }
1 2 Intent service = new Intent(this , MyService.class); startService(service);
开启服务时,调用一次startService()
,生命周期:onCreate()
->onStartCommand()
,调用多次startService()
时,onCreate()
只有第一次会被执行,而onStartCommand()
会被执行多次。结束服务时,调用stopService()
,生命周期执行onDestroy()
方法,调用多次stopService()
时,onDestroy()
只有第一次会被执行。
bindService()
1 2 3 Intent service = new Intent(this , MyService.class); MyConnection conn = new MyConnection(); bindService(service, conn, BIND_AUTO_CREATE);
1 2 3 4 5 6 7 8 9 10 11 private class MyConnection implements ServiceConnection { @Override public void onServiceConnected (ComponentName name, IBinder service) { } @Override public void onServiceDisConnected (ComponentName name) { } }
bindService()
开启服务时,根据生命周期onBind()
返回值是否为空,有两种情况:
为空:通过bindService()
开启服务,生命周期:onCreate()
->onBind()
;调用多次,onCreate()
和onBind()
也只会在第一次被执行。调用unbindService()
结束服务,生命周期:onUnbind()
->onDestroy()
,并且unbindService
只能调用一次,多次调用会抛出异常。调用unbindService()
一定要确保服务已经开启,否则应用会抛异常。
不为空:调用bindService()
,生命周期:onCreate()
->onBind()
->onServiceConnected()
;onBind()
返回的对象会传递到onServiceConnected()
,我们可以利用这个 IBinder 对象进行交互通信。与上一样,unbindService()
和onDestroy
只会执行一次。同一服务可以用两种方式一同开启,没有先后顺序要求,onCreate()
只会执行一。关闭服务需要stopService()
和unbindService()
都被调用,也没有先后顺序之分,onDestroy()
也只会执行一次。如果先调用unbindService()
,此时服务不会自动终止,再调用stopService()
之后,服务才会终止;如果先调用stopService()
,此时服务也不会终止,而再调用unbindService()`
或者之前调用bindService()
的 Context 不存在了(如 Activity被 finish 的时候)之后,服务才会自动停止。
其他: Service 的运行线程(生命周期方法全部在主线程)、ServiceConnection 回调方法也运行于主线程。
参考引用 Android中startService和bindService的区别 startService与bindService的区别