在同一个应用任何地方调用
startService() 方法就能启动 Service 了,然后系统会回调Service 类的
onCreate() 以及 onStart() 方法。这样启动的
Service 会一直运行在后台,直到 Context.stopService() 或者
selfStop() 方法被调用。另外如果一个 Service 已经被启动,其他代码再试图调用
startService() 方法,是不会执行 onCreate() 的,但会重新执行一次
onStart() 。
另外一种
bindService() 方法的意思是,把这个 Service 和调用
Service 的客户类绑起来,如果调用这个客户类被销毁,Service 也会被销毁。用这个方法的一个好处是,bindService()
方法执行后
Service 会回调上边提到的 onBind() 方发,你可以从这里返回一个实现了
IBind 接口的类,在客户端操作这个类就能和这个服务通信了,比如得到 Service 运行的状态或其他操作。如果
Service 还没有运行,使用这个方法启动 Service 就会
onCreate() 方法而不会调用 onStart()。
用其他方式启动
Service
其实不光能从
Activity 中启动 Service ,还有一个很有用的方法是接收系统的广播,这就要用到 Receiver 。在
Mainfest 文件中配置你得 Receiver 能接收什么样的广播消息,那么即使你得程序没有显示给用户,你的 Service 也能启动。你要做的就是继承
android.content.BroadcastReceiver ,然后实现 onReceive(Context context, Intent
intent) 方法,就可以启动你得 Service 了。这里不能
bindService 因为一个 Receiver 是一个短暂存在的对象,所以
bind 是没有什么意义的。
/**
* This is an example of implementing an application service that runs locally
* in the same process as the application. The {@link LocalServiceController}
* and {@link LocalServiceBinding} classes show how to interact with the
* service.
*
*
Notice the use of the {@link NotificationManager} when interesting things
* happen in the service. This is generally how background services should
* interact with the user, rather than doing something more disruptive such as
* calling startActivity().
*/
/**
* Class for clients to access. Because we know this service always
* runs in the same process as its clients, we don't need to deal with
* IPC.
*/ publicclass LocalBinder extends Binder {
LocalService getService(){ return LocalService.this; } }
@Override public IBinder onBind(Intent intent){ return mBinder; }
// This is the object that receives interactions from clients. See
// RemoteService for a more complete example.
privatefinal IBinder mBinder =new LocalBinder();
/**
* Show a notification while this service is running.
*/ privatevoid showNotification(){ // In this sample, we'll use the same text for the ticker and the expanded notification