首先第一个APP 做AIDL的接口及服务,第二个APP再去绑定服务,然后使用AIDL接口中的方法(绑定第一个APP的服务的时候必须先打开第一个APP在后台运行,否则无法绑定) 这里主要是讲 两个应用之间使用AIDL 不会细讲如何创建AIDL的过程及约束。建立在已经过学习过AIDL的朋友之上学习的。
第一个APP:
1、创建一个AIDL文件 ICompute.aidl 然后 声明一个add方法
// ICompute.aidl package com.example.vvv.myaidl1; // Declare any non-default types here with import statements interface ICompute { int add(int a,int b); }2、创建一个服务供第二个APP,然后实现AIDL方法,并以Binder的形式返回给客户端。public class ComputeServer extends Service { @Nullable @Override public IBinder onBind(Intent intent) { return binder; } private IBinder binder = new ICompute.Stub() { @Override public int add(int a, int b) throws RemoteException { return a + b; } }; }这个时候远程服务的代码已经写完了,等待着另外一个进程/APP来启动服务并拿到该接口,然后调用该接口的方法,实现功能,这里是两个数相加第二个APP:
1、绑定服务,然后拿到接口ICompute实例,然后调用该add的方法public class MainActivity extends AppCompatActivity { Button button; ICompute compute; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = (Button) findViewById(R.id.btn); final Intent intent = new Intent(); intent.setComponent(new ComponentName("com.example.vvv.myaidl1", "com.example.vvv.myaidl1.ComputeServer")); bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (null != compute) { int sum = 0; try { sum = compute.add(1, 2); Toast.makeText(MainActivity.this, sum + "--", Toast.LENGTH_LONG).show(); } catch (RemoteException e) { e.printStackTrace(); } } } }); } private ServiceConnection serviceConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { compute = ICompute.Stub.asInterface(service); } @Override public void onServiceDisconnected(ComponentName name) { } }; @Override protected void onDestroy() { super.onDestroy(); unbindService(serviceConnection); } }这时候两个APP的远程调用 已经完成了 。布局什么的比较简单这里代码就不贴出来了。