1、启动状态:A.调用 startService() 方法启动。B.启动状态下的 Service 将会在后台一直运行,即使主应用退出后依旧在运行。C.直到自身通过调用 stopSelf() 结束工作,或者由另一个组件通过调用 stopService() 来停止。D.这种状态下的 Service 一般只负责执行任务,不会直接将结果返回给调用方。E.比如后台下载数据或者处理文件。
2、启动模式的代码:Intent intent = new Intent(this, HelloService.class); startService(intent);startService() 的方式启动服务时,传递 intent 是组件与服务唯一的通信方式,如果还需要返回结果,有几种选择:A.再调用 bindService() 绑定服务。B.为传递的 intent 中添加一个广播,服务端给广播发送结果。
3、绑定状态:A.调用 bindService() 启动。B.绑定状态下的服务可以和调用组件交互,比如发送请求和获取结果。C.这种情况下就可能涉及到 IPC。D.一个服务可以绑定多个组件,有绑定的组件才会运行,绑定的组件全部取消绑定后就销毁。
4、绑定模式启动的代码:private ServiceConnection mConnection = new ServiceConnection() { @Overri颊俄岿髭de public void onServiceConnected(ComponentName name, IBinder service) { mAidl = IMyAidl.Stub.asInterface(service); } @Override public void onServiceDisconnected(ComponentName name) { mAidl = null; } }; Intent intent1 = new Intent(getApplicationContext(), MyAidlService.class); bindService(intent1, mConnection, BIND_AUTO_CREATE);Service 有时会被独自放置到另外一个进程,这时如果我们的应用想与 Service 进行交互,就需要调用 bindService() 方法,因为这样客户端就可以拿到 Service 的 onBind() 方法返回的接口,然后进行操作。