在Android Studio左侧Project栏中,右键src/路径,选择新建aidl文件,命名为IRemoteService.aidl。如果提示Requires setting the buildFeatures.aidl to true in the build file,可以编辑app/路径下的build.gradle.kts文件,在android{...}中添加buildFeatures.aidl = true,并Sync Project with Gradle Files:
// 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); }
/** The primary interface we are calling on the service. */ IRemoteService mService = null; /** * Class for interacting with the main interface of the service. */ private ServiceConnection mConnection = new ServiceConnection() { publicvoidonServiceConnected(ComponentName className, IBinder service){ mService = IRemoteService.Stub.asInterface(service); }
/** The primary interface we are calling on the service. */ IRemoteService mService = null; /** * Class for interacting with the main interface of the service. */ private ServiceConnection mConnection = new ServiceConnection() { publicvoidonServiceConnected(ComponentName className, IBinder service){ // This is called when the connection with the service is // established, giving us the service object we can use to // interact with the service. We are communicating with our // service through an IDL interface, so get a client-side // representation of that from the raw service object. mService = IRemoteService.Stub.asInterface(service); if (mService != null) { try { String text = "Service PID: " + String.valueOf(mService.getPid()) + "\nClient PID: " + Process.myPid(); TextView hello_world = (TextView) findViewById(R.id.hello_world); hello_world.setText(text); } catch (RemoteException e) { thrownew RuntimeException(e); } } }
publicvoidonServiceDisconnected(ComponentName className){ // This is called when the connection with the service is // unexpectedly disconnected—that is, its process crashed. mService = null; } }; }