最近看android的一些知识点,看到AIDL相关,其实AIDL也是messenger的底层实现。首先理解了一下使用场景:1.跨进程,2.多线程并发。下面看一个栗子:
服务端(一个进程):
1.创建接口文件,AIDL文件。在文件中定义好需要暴露的接口:
interface IAdd { int add(int num1,int num2); int multi(int num1,int num2); }2.在一个服务中实现这个接口:
@Override public IBinder onBind(Intent intent) { return mIBinder; } private IBinder mIBinder = new IAdd.Stub() { @Override public int add(int num1, int num2) throws RemoteException { return num1 + num2; } @Override public int multi(int num1, int num2) throws RemoteException { return num1 * num2; } };客户端:
在客户端,需要把服务端定义的AIDL文件包拷贝到客户端中,当然如果服务端和客户端AIDL在一个包中,不需要,要去包aidl的接口所在类的路径一样,不然运行会报错。如下:
private IAdd mAidl; private ServiceConnection conn = new ServiceConnection() { @Override public void onServiceConnected(ComponentName componentName, IBinder iBinder) { mAidl = IAdd.Stub.asInterface(iBinder);//获得接口 } @Override public void onServiceDisconnected(ComponentName componentName) { mAidl = null; } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initWidget(); initAIDL(); } public void addNum(View view) { try { int num1 = Integer.parseInt(etAdd1.getText().toString()); int num2 = Integer.parseInt(etAdd2.getText().toString()); int result = mAidl.add(num1, num2); etAddResult.setText("" + result); } catch (RemoteException e) { e.printStackTrace(); etAddResult.setText("异常了"); } } public void multiNum(View view) { try { int num1 = Integer.parseInt(etMulti1.getText().toString()); int num2 = Integer.parseInt(etMulti2.getText().toString()); int result = mAidl.multi(num1, num2); etMultiResult.setText("" + result); } catch (RemoteException e) { e.printStackTrace(); etMultiResult.setText("异常了"); } } private void initAIDL() { Intent intent = new Intent(); intent.setComponent(new ComponentName("com.wynne.wh.aidl", "com.wynne.wh.aidl.MyService")); bindService(intent, conn, Context.BIND_AUTO_CREATE); } @Override protected void onDestroy() { super.onDestroy(); unbindService(conn); }以上就是简单的使用流程。