我有一个简单的AIDL定义,我想在Kotlin代码中使用,但是当它生成时,会为使用该接口的所有变量显示未解决的引用错误。但是相同的AIDL在Java代码中没有问题。 Kotlin支持吗?怎么解决这是我的AIDL,位于src / main / aidl /
// ServiceInterface.aidl
package com.example.test;
interface ServiceInterface {
void test(String arg1);
}
活动代码为
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.IBinder
import android.os.RemoteException
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.swiftytime.clientappcommunication.R
import com.example.test.ServiceInterface
class MainActivity : AppCompatActivity() {
var mServiceAidl: ServiceInterface? = null
var mIsBound = false
private val mConnection: ServiceConnection = object : ServiceConnection {
override fun onServiceConnected(className: ComponentName, service: IBinder) {
try {
mServiceAidl = ServiceInterface.Stub.asInterface(service)
Log.e("app", "Attached")
} catch (e: RemoteException) {
}
}
override fun onServiceDisconnected(className: ComponentName) {
mServiceAidl = null
Log.e("app", "Disconnected.")
}
}
private fun doBindService() {
val intent = Intent().apply {
component = ComponentName(
"com.example.test", "com.example.test.MyService"
)
}
bindService(
intent,
mConnection, Context.BIND_AUTO_CREATE
)
mIsBound = true
Log.e("app", "Binding.")
}
private fun doUnbindService() {
if (mIsBound) {
unbindService(mConnection)
mIsBound = false
Log.e("app", "Unbinding.")
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
doBindService()
}
}
这是错误
[ERROR] [org.gradle.api.Task] e: /Volumes/Projects/AndroidProject/ClientAppCommunication/app/src/main/java/com/example/test/MainActivity.kt: (16, 23): Unresolved reference: ServiceInterface
[许多小时后,我发现问题是buildToolsVersion 29.0.0为生成的Java文件生成了错误的路径,我提交了bug
只需更改为buildToolsVersion 28.0.3即可解决问题。
更新:已解决问题,现在可以在buildToolsVersion 29.0.1
我在Kotlin中使用AIDL,我所拥有的是用Java编写的接口,并且已定义接口使用的所有模型类都在Kotlin中编写,并且运行良好。例如。我有方法*>的I * Subscriber.aidl
void onSomeEventHappened(in AidlEvent event);
还有AidlEvent类的.aidl文件和.kt文件。
AidlEvent.aidl文件
// AidlEvent.aidl parcelable AidlEvent;
AidlEvent.kt
data class AidlEvent( val eventType: Int, val eventMessage: String): Parcelable { // add parcelable methods }
我不确定您是否能够在Kotlin中编写.aidl接口,但还没有做到这一点。如果您需要用Java编写一些方法,这不是问题,因为您不需要在Java中实现它们,只需声明它们即可。