万书网 > 文学作品 > Android从入门到精通 > 第146页

第146页


try  {



messenger.send(msg);



}  catch  (RemoteException  e)  {



e.printStackTrace();



}



}



@Override



protected  void  onCreate(Bundle  savedInstanceState)  {



super.onCreate(savedInstanceState);



setContentView(R.layout.main);



}



@Override



protected  void  onStart()  {



super.onStart();



bindService(new  Intent(this,  MessengerService.class),  connection,  Context.BIND_AUTO_CREATE);



}



@Override



protected  void  onStop()  {



super.onStop();



if  (bound)  {



unbindService(connection);



bound  =  false;



}



}



}

该实例并没有演示服务如何响应客户端。如果希望服务响应,则需要在客户端也创建Messenger。当客户端收到onServiceConnected()回调方法时,发送Message到服务。Message的replyTo成员变量包含客户端的Messenger。

13.3.3 绑定到服务

应用程序组件(客户端)能调用bindService()方法绑定到服务,接下来Android系统调用服务的onBind()方法,返回IBinder来与服务通信。

绑定是异步的。bindService()方法立即返回并且不返回IBinder到客户端。为了接收IBinder,客户端必须创建ServiceConnection实例,然后将其传递给bindService()方法。ServiceConnection包含系统调用发送IBinder的回调方法。

注意:  只有Activity、Service和ContentProvider能绑定到服务,BroadcastReceiver不能绑定到服务。

如果需要从客户端绑定服务,需要完成以下操作:

(1)实现ServiceConnection,这需要重写onServiceConnected()和onServiceDisconnected()两个回调方法。

(2)调用bindService()方法,传递ServiceConnection实现。

(3)当系统调用onServiceConnected()回调方法时,就可以使用接口定义的方法调用服务。

(4)调用unbindService()方法解绑定。

当客户端销毁时,会将其从服务上解绑定。但是当与服务完成交互或者Activity暂停时,最好解绑定,以便系统能及时停止不用的服务。

13.3.4 实例1:继承Binder类绑定服务显示时间

例13.3   在Eclipse中创建Android项目,名称为13.3,实现继承Binder类绑定服务,并显示当前时间。(实例位置:光盘\TM\sl\13\13.3)

(1)修改res\layout目录中的main.xml布局文件,设置背景图片并添加一个按钮,然后设置按钮文字的内容、颜色和大小,其代码如下:








android:layout_width="fill_parent"



android:layout_height="fill_parent"



android:background="@drawable/background"



android:orientation="vertical"  >






android:id="@+id/current_time"



android:layout_width="wrap_content"



android:layout_height="wrap_content"



android:text="@string/current_time"



android:textColor="@android:color/black"



android:textSize="25dp"  />





(2)创建CurrentTimeService类,它继承了Service类。内部类LocalBinder继承了Binder类,用于返回CurrentTimeService类的对象。getCurrentTime()方法用于返回当前时间,其代码如下:

public  class  CurrentTimeService  extends  Service  {



private  final  IBinder  binder  =  new  LocalBinder();



public  class  LocalBinder  extends  Binder  {



CurrentTimeService  getService()  {



return  CurrentTimeService.this;  //返回当前服务的实例



}



}



@Override



public  IBinder  onBind(Intent  arg0)  {



return  binder;



}



public  String  getCurrentTime()  {



Time  time  =  new  Time();  //创建Time对象



time.setToNow();  //设置时间为当前时间



String  currentTime  =  time.format("%Y-%m-%d  %H:%M:%S");  //设置时间格式



return  currentTime;



}



}

注意:  此处使用的时间格式与Java  API中SimpleDateFormat类有所不同。

(3)创建CurrentTimeActivity类,它继承了Activity类。在onCreate()方法中设置布局。在onStart()方法中,获得按钮控件并增加单击事件监听器。在监听器中,使用bindService()方法绑定服务。在onStop()方法中解除绑定,其代码如下:

public  class  CurrentTimeActivity  extends  Activity  {



CurrentTimeService  cts;



boolean  bound;



@Override



protected  void  onCreate(Bundle  savedInstanceState)  {