绑定式服务:适合客户端和服务器端数据接口的交互。下面我们以绑定service并调用service中的方法返回结果为背景介绍它的使用方法。
整体思路:在xml文件中放置一个TextView控件、两个Button控件,在MainActivity中实例化一个ServiceConnection类,在这个类中重写onServiceDisconnected和onServiceConnected方法,在onServiceDisconnected方法中设置绑定状态为false,在onServiceConnected方法中获取service实例并设置绑定状态为true;在onStop方法中解除对service的绑定,定义两个Button的点击事件,在一个点击事件中绑定service,在第二个点击事件中调用service的方法获取数据并绑定到TextView控件上。定义一个MyService类,继承Service类,在这个类中定义LocalBinder类,返回service实例,并定义提供给MainActivity调用的方法。
activity_main.xml文件:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height=