【一】使用Service


这节课程内容包括:使用Service、绑定Service、Service的生命周期


Activity能够呈现用户界面,与用户进行交互,

而很多时候,我们程序不需要与用户交互,只需要一直在后台运行,

做一些事物处理,例如:Socket长连接、Http网络通信、与服务器保持推送的连接。


如何创建Service?

建一个继承于Service的子类,然后在AndroidManifest.xml中配置即可。

publicclassMyServiceextendsService{publicIBinderonBind(Intentintent){thrownewUnsupportOperationException("Notyetimplemented");}}


<Serviceandroid:name=".MyService"android:enabled="true"android:exported="Service"></Service>

android:exported —— 是否向外界公开

android:enabled —— 是否启用


如何启动Service?

新建一个Button,在MainActivity中给它设置一个事件监听器,然后

startService(newIntent(MainActivity.this,MyService.class));

这样就能启动服务,接下来建一个停止服务的Button,写上

stopService(newIntent(MainActivity.this,MyService.class))

疑问:启动和停止都创建了一个Intent,这两个新创建的Intent实例,是否操作是同一个服务呢?

回答:是同一个服务。因为服务的实例,在操作系统上,只可能有那么一个。

把Intent定义为成员变量,startService和stopService都传入这同一个Intent,效果还是一样的,

因为Intent只是用来配置程序要启动Service的信息的,具体所要操作的Service还是同一个Service。


在"系统设置"-"应用"-"运行中"就可以看我们写的服务是否启动。


现在补充一下,让我们的Service在后台不断执行输出语句,

这需要重写onStartCommand方法:

publicclassMyServiceextendsService{publicIBinderonBind(Intentintent){thrownewUnsupportOperationException("Notyetimplemented");}@OverridepublicintonStartCommand(Intentintent,intflags,intstartId){newThread(){publicvoidrun(){super.run();while(true){System.out.println("服务正在运行");}try{sleep(100);}catch(InterruptedExceptione){e.printStackTrace();}}}.start();returnsuper.onStartCommand(intent,flag,startId);}}

这样,如果启动了服务,就算Activity已经退出,它仍然会在后台执行。


【二】绑定Service


启动Service还能用绑定Service的方式来启动,如何绑定?

在MainActivity加两个Button,一个"BindService",一个"UnBindService"。

它们触发的方法分别是bindService()和unbindService()。


bindService()有三个参数,Intent、服务的连接(用于监听服务的状态,这里传入)、传一个常量Context.BIND_AUTO_CREATE。

第二个参数需要MainActivity实现ServiceConnection接口,需要实现重写以下的方法:

@OverridepublicvoidonServiceConnected(ComponentNamename,IBinderservice){Toast.makeText(MainActivity.this,"onServiceConnected",Toast.LENGTH_SHORT).show();}@OverridepublicvoidonServiceDisconnected(ComponentNamename){}

onServiceConnected在服务被绑定成功时执行,

onServiceDisconnected在服务所在进行崩溃或被杀掉时被执行。


unbindService()的参数就是this。


接下来执行程序,会发现出错:

java.lang.RuntimeException: Unable to bind to service com.linww.demo.learnservice.MyService@23e111e3 with Intent { cmp=com.linww.demo.learnservice/.MyService }: java.lang.UnsupportedOperationException: Not yet implemented


通过查看发现是onBind这里抛异常,在这方法返回一个Binder()对象就OK了。

@OverridepublicIBinderonBind(Intentintent){//TODO:Returnthecommunicationchanneltotheservice.//thrownewUnsupportedOperationException("Notyetimplemented");returnnewBinder();}


【三】Service的生命周期


服务生命周期只需要记得有 onCreate()和onDestroy()。


规律:同时启动服务并且绑定服务,必须同时停止和解除绑定,服务才能被停止。


如果Activity与某一个Service绑定,那么退出这个Activity,Service也会被取消绑定。


关于onStartCommand()方法,如果Service第一次启动,是onCreate()后执行onStartCommand();

而如果Service已经被启动过了,那么再去启动它,例如点击启动按钮,

则只会执行onStartCommand(),不会重复执行onCreate()。