Service基础
Servie方法
onCreate: 创建服务 (第一次 startService的时候调用)
onStart: 开启服务 (过时的方法, 新方法是 onStartCommand)
onStartCommand: 开启服务 (每次 startService的时候都调用)
onDestroy: 销毁服务 (只有先 startService再 stopService才会调用 onDestroy方法)
onBind: 绑定服务
onUnbind: 解绑服务
onRebind: 重新绑定服务
Service两种启动方式
startService
- 生命周期: onCreate -> onStartCommand -> onDestroy
- 启动方式: startService启动 Service, stopService销毁 Service
- 第一次调用 startService, 会调用 onCreate和 onStartCommand方法, 但第二次调用 startService时, 只会调用 onStartCommand方法
- 只有先调用 startService再调用 stopService, onDestroy方法才会被执行
bindService
- 生命周期: onCreate -> onBind -> onUnbind -> onDestroy
- 启动方式: 调用 bindService绑定服务, UnbindService 解绑服务, StopService销毁服务
如果是 bindService进行服务的启动, 那么只能先UnbindService, 再StopService
intent = new Intent(this, MyService.class); MyConnection conn = new MyConnection(); bindService(intent, conn, BIND_AUTO_CREATE); class MyConnection implements ServiceConnection{ //服务连接建立时,此方法调用。绑定服务,其实就是连接到服务。onBind有返回值才会调用 @Override public void onServiceConnected(ComponentName name, IBinder service) { // TODO Auto-generated method stub } //失去服务连接时调用 @Override public void onServiceDisconnected(ComponentName name) { // TODO Auto-generated method stub } }