Android IntentService的依赖注入不';行不通
我想创建TCP_客户端,它在许多活动中向服务器发送数据。我决定使用依赖注入将所有配置相同的客户端注入到所有客户端。不幸的是,它在启动时停止工作 我的应用程序模块Android IntentService的依赖注入不';行不通,android,kotlin,dependency-injection,koin,Android,Kotlin,Dependency Injection,Koin,我想创建TCP_客户端,它在许多活动中向服务器发送数据。我决定使用依赖注入将所有配置相同的客户端注入到所有客户端。不幸的是,它在启动时停止工作 我的应用程序模块 val appModule = module { single<ConnectionService> { ConnectionServiceTcp("192.168.0.1", 8888) } } 然后我收到 java.lang.RuntimeException: Unable to instantiate
val appModule = module {
single<ConnectionService> { ConnectionServiceTcp("192.168.0.1", 8888) }
}
然后我收到
java.lang.RuntimeException: Unable to instantiate service connection.impl.ConnectionServiceTcp: java.lang.InstantiationException: java.lang.Class<connection.impl.ConnectionServiceTcp> has no zero argument constructor
java.lang.RuntimeException:无法实例化服务连接。impl.ConnectionServiceCp:java.lang.InstanceException:java.lang.Class没有零参数构造函数
我找不到一种方法来注入后台客户端来发送TCP请求就像活动、片段或其他一些平台组件一样,Android系统意味着服务应该有一个单一的无参数构造函数。系统在服务类中查找默认构造函数,并使用反射调用它。这就是为什么禁止添加非默认构造函数(即带参数的构造函数) 要将依赖项注入到服务中,您应该像在活动中一样(声明一个字段并使用by inject()delegate将其注入)。因此最终代码如下所示:
class ConnectionServiceTcp()
: IntentService("TCP_CLIENT"), ConnectionService {
private val ipAddress: String by inject()
private val port : Int by inject()
private var client : Socket? = null
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
super.onStartCommand(intent, flags, startId)
return START_STICKY
}
override fun onHandleIntent(intent: Intent?) {
startTcpServer()
}
private fun startTcpServer() {
client = Socket(ipAddress, port)
}
override fun isConnectedToServer(): Boolean {
Log.println(Log.INFO, null, "Adres = ${client?.localAddress} port = ${client?.localPort}")
return false
}
}
class MainActivity : AppCompatActivity() {
private val connectionService : ConnectionService by inject()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
startTcpServer()
}
private fun startTcpServer() {
val serverTcp = Intent(this, ConnectionServiceTcp::class.java)
startService(serverTcp)
}
java.lang.RuntimeException: Unable to instantiate service connection.impl.ConnectionServiceTcp: java.lang.InstantiationException: java.lang.Class<connection.impl.ConnectionServiceTcp> has no zero argument constructor
class ConnectionServiceTcp()
: IntentService("TCP_CLIENT"), ConnectionService {
private val ipAddress: String by inject()
private val port : Int by inject()
private var client : Socket? = null
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
super.onStartCommand(intent, flags, startId)
return START_STICKY
}
override fun onHandleIntent(intent: Intent?) {
startTcpServer()
}
private fun startTcpServer() {
client = Socket(ipAddress, port)
}
override fun isConnectedToServer(): Boolean {
Log.println(Log.INFO, null, "Adres = ${client?.localAddress} port = ${client?.localPort}")
return false
}
}