【发布时间】:2019-11-15 19:11:57
【问题描述】:
我想创建在许多活动中向服务器发送数据的 TCP_Client。我决定使用依赖注入将所有配置相同的客户端注入所有客户端。不幸的是,它在开始时停止工作。
我的应用模块
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
我找不到注入后台客户端以发送 TCP 请求的方法
【问题讨论】:
标签: android kotlin dependency-injection koin