AIDL一般用于跨进程通讯,和Service相关。服务端提供一个Service来处理客户端连接。首先写一个远程服务工程,创建一个远程服务类,定义一个接口,使Service的中间人对象Binder继承接口,实现接口的方法并在该方法中调用Service中的方法。
interface Iservice { void callMethod(); } public class MyService extends Service { @Override public IBinder onBind(Intent intent) { // TODO Auto-generated method stub return new MyBinder(); } public void method() { System.out.println("我是其他进程的方法"); } private class MyBinder extends Stub { @Override public void callMethod() throws RemoteException { method(); } } }在本地工程中导入远程服务的AIDL文件,通过远程服务Service在清单文件中配置的action来关联远程服务,并且拿到传递过来的接口对象(中间人对象)。通过接口对象就可以调用远程服务里的方法。
public class MainActivity extends Activity { private Iservice iservice; private MyConn conn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Intent service = new Intent(); service.setAction("com.itheima.service"); conn = new MyConn(); bindService(service, conn, BIND_AUTO_CREATE); } @Override protected void onDestroy() { unbindService(conn); super.onDestroy(); } public void click(View v) { System.out.println("我是自己进程的方法"); try { iservice.callMethod(); } catch (RemoteException e) { // TODO Auto-generated catch block e.printStackTrace(); } } class MyConn implements ServiceConnection { @Override public void onServiceConnected(ComponentName name, IBinder service) { iservice = Stub.asInterface(service); } @Override public void onServiceDisconnected(ComponentName name) { } } }注意:记得在本地工程销毁时解绑服务,远程服务中的方法必须是public,不然不能直接调用该方法。
