gpt4 book ai didi

android - IntentService 的依赖注入(inject)不起作用

转载 作者:行者123 更新时间:2023-11-30 04:57:30 29 4
gpt4 key购买 nike

我想创建 TCP_Client,它在许多 Activity 中将数据发送到服务器。我决定使用依赖注入(inject)将所有相同配置的客户端注入(inject)到所有客户端。不幸的是,它在开始时停止工作。

我的应用程序模块

val appModule = module {
single<ConnectionService> { ConnectionServiceTcp("192.168.0.1", 8888) }
}

主要应用

class MainApplication : Application() {

override fun onCreate() {
super.onCreate()
startKoin {
androidContext(this@MainApplication)
androidLogger()
modules(appModule)
}
}
}
class ConnectionServiceTcp(private val ipAddress: String, private val port : Int)
: IntentService("TCP_CLIENT"), ConnectionService {

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

我找不到注入(inject)后台客户端发送 TCP 请求的方法

最佳答案

就像 Activities、Fragments 或其他一些平台组件一样,Android 系统暗示服务应该有一个单一的无参数构造函数。系统在 Service 类中查找默认构造函数并使用反射调用它。这就是为什么禁止添加非默认构造函数(即带参数的构造函数)的原因。

要将依赖项注入(inject)服务,您应该像在 Activity 中一样执行操作(声明一个字段并使用 by inject() 委托(delegate)注入(inject)它。因此最终代码如下所示:

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
}
}

关于android - IntentService 的依赖注入(inject)不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58883288/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com