// Declare any non-default types here with import statements.
/** Example service interface */ interfaceIRemoteService { /** Request the process ID of this service. */ intgetPid();
/** Demonstrates some basic types that you can use as parameters * and return values in AIDL. */ voidbasicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString); }
// Called when the connection with the service is established overridefunonServiceConnected(className: ComponentName, service: IBinder) { // Following the example above for an AIDL interface, // this gets an instance of the IRemoteInterface, which we can use to call on the service iRemoteService = IRemoteService.Stub.asInterface(service) }
// Called when the connection with the service disconnects unexpectedly overridefunonServiceDisconnected(className: ComponentName) { Log.e(TAG, "Service has unexpectedly disconnected") iRemoteService = null } }
通过 IPC 传递对象
Rect.aidl 文件可创建 Parcelable 类型的 Rect 类:
package android.graphics;
// Declare Rect so AIDL can find it and knows that it implements // the parcelable protocol. parcelable Rect;
/** Example service interface */ interfaceIRectInsideBundle { /** Rect parcelable is stored in the bundle with key "rect" */ voidsaveRect(in Bundle bundle); }
读取 Rect 前在 Bundle 中完成 ClassLoader 设置。
privateval binder = object : IRectInsideBundle.Stub() { overridefunsaveRect(bundle: Bundle) { bundle.classLoader = classLoader val rect = bundle.getParcelable<Rect>("rect") process(rect) // Do more with the parcelable } }