绑定远程服务

来源:互联网 发布:苏联陈兵百万知乎 编辑:程序博客网 时间:2024/06/05 00:19

1.在activity里面调用bindService()去绑定服务。

bindService(intent, new MyConn(), BIND_AUTO_CREATE);

需要传递一个叫ServiceConnection的接口参数

用来返回两个回调:

当前服务被成功绑定

当前服务失去连接

2.在服务里面需要重写onBind()方法,在服务被绑定的时候调用 返回一个IBInder接口对象(代理人

接口定义需要改成aidl格式,用自动生成的IService.Stub代理人,接口里面必须实现一个方法,该方法可以调用到服务里面的方法。

3.在activity的onServiceConnected得到中间人,使用aidl自动生成的IService,利用IService.Stub.asInterface();

4.中间人调用服务的方法。



远程服务:

下面是远程服务的服务类:

public class AlipayService extends Service {private class MyBinder extends IService.Stub{@Overridepublic void callMethodInService() {methodInService();}}private void methodInService(){System.out.println("methodInService:正在进行支付宝安全服务。。");}@Overridepublic IBinder onBind(Intent arg0) {System.out.println("onBind:服务被绑定了。。。");return new MyBinder();}@Overridepublic boolean onUnbind(Intent intent) {System.out.println("onUnbind:服务被解除绑定了。。。");return super.onUnbind(intent);}@Overridepublic void onCreate() {System.out.println("onCreate:服务被创建了。。。");super.onCreate();}@Overridepublic void onDestroy() {System.out.println("onDestroy:服务被销毁了。。。");super.onDestroy();}}

接口IService,aidl后缀名

package com.example.alipay;interface IService {void callMethodInService();}




将远程服务里面服务类所在包名和IService.aidl接口复制到访问pro。




访问远程服务的代码:

public class MainActivity extends Activity {private Intent intent;private IService iService;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);intent = new Intent();intent.setAction("com.example.alipay");}public void bind(View view){bindService(intent, new MyConn(), BIND_AUTO_CREATE);}private class MyConn implements ServiceConnection{@Overridepublic void onServiceConnected(ComponentName arg0, IBinder service) {// TODO Auto-generated method stubiService = IService.Stub.asInterface(service);}@Overridepublic void onServiceDisconnected(ComponentName arg0) {// TODO Auto-generated method stub}}public void callMethod(View view){try {iService.callMethodInService();} catch (RemoteException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}


原创粉丝点击