Android AIDL Example in KotlinSep 13th 2020Words: 929
This post is created a year ago, the content may be outdated.
Background
I am working on an Android app that I want part of the function being delivered in an additional plugin. This plugin does not have any activity, it only provides service for my main app. Therefore, I need a method to enable my main app communicating with the plugin. AIDL is exactly what I am looking for.
Note: Using AIDL is necessary only if you allow clients from different applications to access your service for IPC and want to handle multithreading in your service. If you do not need to perform concurrent IPC across different applications, you should create your interface by implementing a Binder or, if you want to perform IPC, but do not need to handle multithreading, implement your interface using a Messenger. Regardless, be sure that you understand Bound Services before implementing an AIDL.
Other choices of IPC are:
File
AIDL
Binder
Messenger
Content Provider
Socket
Server Code
The server only has a service with one function, to echo the argument to the caller.
IMyServiceInterface.aidl
1 2 3 4 5 6 7 8
package com.example.myplugin;
// Declare any non-default types here with import statements
classMainActivity : AppCompatActivity() { var iInputService: IMyServiceInterface? = null val mConnection = object : ServiceConnection { // 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 iInputService = IMyServiceInterface.Stub.asInterface(service) Toast.makeText(applicationContext, "Service bind success", Toast.LENGTH_SHORT).show() }
// Called when the connection with the service disconnects unexpectedly overridefunonServiceDisconnected(className: ComponentName) { iInputService = null Toast.makeText(applicationContext, "Service disconnected", Toast.LENGTH_SHORT).show() } }
// bind service on activity create val intent = Intent() intent.setClassName("com.example.myplugin", "com.example.myplugin.InputService"); // Must use explicit intent bindService(intent, mConnection, Context.BIND_AUTO_CREATE)
// Call remote function on button click val button: Button = findViewById(R.id.button) button.setOnClickListener {
val result = iInputService?.test((1..100).random()) Toast.makeText(applicationContext, """Call result: $result""", Toast.LENGTH_SHORT) .show() } }
overridefunonDestroy() { super.onDestroy() unbindService(mConnection); // Unbind service on activity destroy } }