Service基础

Service 没有用户界面,在后台运行。

启动Service有两种方式
1. startService()启动Service,Service会在后台不确定的运行,生死与调用者无关。
2. bindService()绑定Service,类似client-server模式,当所有客户端都取消绑定时,Service停止。

Service中需要处理一些系统回调方法
1. onStartCommand():The system calls this method when another component, such as an activity, requests that the service be started, by calling startService(). Once this method executes, the service is started and can run in the background indefinitely. If you implement this, it is your responsibility to stop the service when its work is done, by calling stopSelf() or stopService().(If you only want to provide binding, you don't need to implement this method.)

2. onBind():The system calls this method when another component wants to bind with the service (such as to perform RPC), by calling bindService(). In your implementation of this method, you must provide an interface that clients use to communicate with the service, by returning an IBinder. You must always implement this method, but if you don't want to allow binding, then you should return null.

3. onCreate():The system calls this method when the service is first created, to perform one-time setup procedures (before it calls either onStartCommand() or onBind()). If the service is already running, this method is not called.

4. onDestroy():The system calls this method when the service is no longer used and is being destroyed. Your service should implement this to clean up any resources such as threads, registered listeners, receivers, etc. This is the last call the service receives.

参看Android Developers官网

你可能感兴趣的:(android,service)