Local Bound Service Remote Bound Service

 

               首先创建子类 BoundService 继承 Service; 在BoundService 中创建子类 MyBinder 继承 Binder; Binder的作用就是进程内或进程之间 service 和client 交互的媒介(我现在暂时这么认为), MyBinder 中 实现         getService()的方法, 返回当前BoundService; 在要使用Service的Activity中 使用bindService (); 此时,你需要创建一个 ServiceConnection 去连接Activity 和 Service 。 改写ServiceConnection的2个方法

           public void onServiceConnected(ComponentName className,IBinder service) //service即为 Service onBinder() 返回的IBinder 类型变量

 

          和public void onServiceDisconnected(ComponentName arg0)

Local 和 Remote 的区别在于 new Intent 去创建的方式 Local :Intent intent = new Intent(this,BoundService.class); //通过本地的类 直接启动 Service Remote: Intent intent=new Intent("com.example.RemoteService");// 通过 Service的包名 在Remote Bound Service 中 关键是 public void onServiceConnected(ComponentName className,IBinder service){ 将Messenger 变量(handle message) myService =new Messenger(service); //service 为 启动的Service onBind()返回的 IBinder 接口

posted on 2014-02-11 14:49  小白说我是2B  阅读(203)  评论(0编辑  收藏  举报

导航