时间:2021-11-05 09:22:48 | 栏目:Android代码 | 点击:次
AIDL是Android接口定义语言,它可以用于让某个Service与多个应用程序组件之间进行跨进程通信,从而可以实现多个应用程序共享同一个Service的功能。
实现步骤
例:用 A程序去访问 B程序的MyService.java服务
对应步骤详细代码:
MyAidlService.AIDL
interface MyAidlService { int add(int a, int b); }
MyService.Java
public class MyService extends Service{ MyAidlService.Stub mBinder = new MyAidlService.Stub() { @Override public int add(int a, int b) throws RemoteException { return a + b; } }; @Override public IBinder onBind(Intent intent) { return mBinder; } @Override public void onCreate() { super.onCreate(); } @Override public void onDestroy() { super.onDestroy(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { return super.onStartCommand(intent, flags, startId); } }
3.添加action
<service android:name=".MyService"> <intent-filter> <action android:name="com.xyb.servicetest.MyAidlService"/> </intent-filter> </service>
4.拷贝AIDL文件夹
5.A访问B的服务
Intent intent = new Intent("com.xyb.servicetest.MyAidlService"); bindService(intent, connection, BIND_AUTO_CREATE);
private MyAidlService aidlService;
private ServiceConnection connection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { Log.d("onServiceConnected", "onServiceConnected"); aidlService = (MyAidlService) MyAidlService.Stub.asInterface(service); try { int sum = aidlService.add(10, 50);//对10和50相加 Log.d("onServiceConnected", sum + ""); } catch (RemoteException e) { e.printStackTrace(); } } @Override public void onServiceDisconnected(ComponentName name) { } };