1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| AIDL(Android Interface Definition Language)用于 自动生成 Binder 代码,简化 IPC 实现。
AIDL 使用步骤: 1 创建 AIDL 接口(IMyService.aidl): interface IMyService { void sendData(String msg); }
2 在服务端实现 AIDL: public class MyService extends Service { private final IMyService.Stub mBinder = new IMyService.Stub() { @Override public void sendData(String msg) { Log.d("MyService", "Received: " + msg); } };
@Override public IBinder onBind(Intent intent) { return mBinder; } } 3 客户端绑定服务并调用 AIDL 方法 ServiceConnection connection = new ServiceConnection() { public void onServiceConnected(ComponentName name, IBinder service) { IMyService myService = IMyService.Stub.asInterface(service); myService.sendData("Hello Binder"); } }; bindService(new Intent(this, MyService.class), connection, Context.BIND_AUTO_CREATE);
|