android - 使用 IntentService 进行依赖注入不起作用
问题描述
我想创建 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 系统暗示服务应该有一个单一的无参数构造函数。系统在 Service 类中查找默认构造函数并使用反射调用它。这就是为什么禁止添加非默认构造函数(即带参数的构造函数)的原因。
要将依赖项注入到服务中,您应该执行与活动中相同的操作(声明一个字段并使用注入()委托注入它。因此最终代码将如下所示:
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
}
}
推荐阅读
- node.js - 放大发布不断失败,并出现 spawn npm.cmd ENOENT 错误
- database - 该关系满足的更高范式
- c# - C# OpenFileDialog/CommonOpenFileDialog
- linux - 在 Linux Shell 中,如何找出我最常使用的命令以及使用频率?
- google-app-engine - 您可以在 Go 1.12+ 运行时使用 App Engine Standard 上的 `context.Background()` 吗?
- c# - 如何从asp net c#后面的代码清除/重置用户控件中的所有子控件
- c++ - 在 C/C++ 中,如何就地编辑文件?
- docker - 如果您运行已构建的 Docker 映像,Docker 映像的父映像是否会从其存储库中隐式提取?
- autocomplete - HERE API 自动完成不会返回墨西哥城
- c++ - 当我声明的所有内容都是双重形式时,为什么我的输出不是双重形式?