从上一篇文章我们学会了如何创建Service,我们通过监听一个按钮,然后再按钮里面通过意图来启动Service。但是我们有没有发现,启动服务以后,Activity和Service之间的联系好像就断开了。两个组建么有太多的关联。那么,这一篇文章我们来介绍,服务和活动之间的绑定。BYW,服务可以和任何一个活动绑定,而且绑定后都可以获取到相同的Binder实例。
关于服务的一点小知识:
一个服务,如果我们调用了startService(),然后再去调用stopService(),那么onDestroy()就会执行,
如果我们调用了bindService()方法后,又去调用unbindService(),那么onDestroy()就也执行,
但是,如果你同时调用了startService()和bindService(),然后只是调用了stopService()或只是调用了unbindService(),那么onDestory()是不会执行的。也就是说,如果你同时调用了startService()和bindService(),那么你就必须同时调用stopService()和unbindService(),onDestory()才会执行。
下面我们还是一样,先看代码吧.
首先是布局文件,布局文件没什么,就是放置四个按钮而已
1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 2 xmlns:tools="http://schemas.android.com/tools" 3 android:layout_width="match_parent" 4 android:layout_height="match_parent" 5 android:orientation="vertical" 6 android:paddingBottom="@dimen/activity_vertical_margin" 7 android:paddingLeft="@dimen/activity_horizontal_margin" 8 android:paddingRight="@dimen/activity_horizontal_margin" 9 android:paddingTop="@dimen/activity_vertical_margin" 10 tools:context="com.example.servicedemo.MainActivity" > 11 12 <Button 13 android:onClick="onclick" 14 android:id="@+id/bt_start" 15 android:layout_width="match_parent" 16 android:layout_height="wrap_content" 17 android:text="开启服务" 18 /> 19 20 <Button 21 android:onClick="onclick" 22 android:id="@+id/bt_stop" 23 android:layout_width="match_parent" 24 android:layout_height="wrap_content" 25 android:text="关闭服务" 26 /> 27 28 <Button 29 android:onClick="onclick" 30 android:id="@+id/bt_bind" 31 android:layout_width="match_parent" 32 android:layout_height="wrap_content" 33 android:text="绑定服务" 34 /> 35 36 <Button 37 android:onClick="onclick" 38 android:id="@+id/bt_unbind" 39 android:layout_width="match_parent" 40 android:layout_height="wrap_content" 41 android:text="解绑服务" 42 /> 43 44 45 </LinearLayout>