goman 发表于 2013-8-28 16:29

android的Service学习

2Android中的服务,它与Activity不同,它是不能与用户交互的,不能自己启动的,运行在后台的程序,如果我们退出应用时,Service进程并没有结束,它仍然在后台运行,那 我们什么时候会用到Service呢?比如我们播放音乐的时候,有可能想边听音乐边干些其他事情,当我们退出播放音乐的应用,如果不用Service,我 们就听不到歌了,所以这时候就得用到Service了,又比如当我们一个应用的数据是通过网络获取的,不同时间(一段时间)的数据是不同的这时候我们可以 用Service在后台定时更新,而不用每打开应用的时候在去获取。 :Android Service的生命周期并不像Activity那么复杂,它只继承了onCreate(),onStart(),onDestroy()三个方法,当我们第一次启动Service时,先后调用了onCreate(),onStart()这两个方法,当停止Service时,则执行onDestroy()方法,这里需要注意的是,如果Service已经启动了,当我们再次启动Service时,不会在执行onCreate()方法,而是直接执行onStart()方法,具体的可以看下面的实例。Service后端的数据最终还是要呈现在前端Activity之上的,因为启动Service时,系统会重新开启一个新的进程,这就涉及到不同进程间通信的问题了(AIDL)这一节我不作过多描述,当我们想获取启动的Service实例时,我们可以用到bindService和onBindService方法,它们分别执行了Service中IBinder()和onUnbind()方法。下面,我们以一个简单的例子,来讲解下service组件的基本的服务 Main.xml&lt;RelativeLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;    xmlns:tools=&quot;http://schemas.android.com/tools&quot;    android:layout_width=&quot;match_parent&quot;    android:layout_height=&quot;match_parent&quot;   &gt;     &lt;Button      android:id=&quot;@+id/btn_startservice&quot;      android:layout_width=&quot;fill_parent&quot;      android:layout_height=&quot;wrap_content&quot;      android:layout_alignParentLeft=&quot;true&quot;      android:layout_alignParentTop=&quot;true&quot;      android:text=&quot;开始服务&quot; /&gt;    &lt;Button      android:id=&quot;@+id/btn_stopservice&quot;      android:layout_width=&quot;fill_parent&quot;      android:layout_height=&quot;wrap_content&quot;      android:layout_alignLeft=&quot;@+id/btn_startservice&quot;      android:layout_below=&quot;@+id/btn_startservice&quot;      android:layout_marginTop=&quot;55dp&quot;      android:text=&quot;停止服务&quot; /&gt;    &lt;Button         android:id=&quot;@+id/btn_bind&quot;         android:layout_width=&quot;fill_parent&quot;         android:layout_height=&quot;wrap_content&quot;         android:layout_alignLeft=&quot;@+id/btn_stopservice&quot;         android:layout_below=&quot;@+id/btn_stopservice&quot;         android:layout_marginTop=&quot;48dp&quot;         android:text=&quot;绑定服务&quot; /&gt;    &lt;Button         android:id=&quot;@+id/btn_unbind&quot;         android:layout_width=&quot;fill_parent&quot;         android:layout_height=&quot;wrap_content&quot;         android:layout_below=&quot;@+id/btn_bind&quot;         android:layout_marginTop=&quot;45dp&quot;         android:text=&quot;解除绑定&quot; /&gt;     &lt;/RelativeLayout&gt; </div
页: [1]
查看完整版本: android的Service学习