Java 为什么BoundService为空?
我对安卓非常陌生,尝试创建简单的服务。我检查了一个试图 但我不能开始服务。服务始终为空。程序未调用Java 为什么BoundService为空?,java,android,kotlin,Java,Android,Kotlin,我对安卓非常陌生,尝试创建简单的服务。我检查了一个试图 但我不能开始服务。服务始终为空。程序未调用boundServiceConnection函数 这是我的代码服务代码 class BoundService : Service() { private val localBinder: IBinder = MyBinder() override fun onBind(intent: Intent): IBinder? { return localBinder } fu
boundServiceConnection
函数
这是我的代码服务代码
class BoundService : Service() {
private val localBinder: IBinder = MyBinder()
override fun onBind(intent: Intent): IBinder? {
return localBinder
}
fun randomGenerator(): Int {
val randomNumber = Random()
return randomNumber.nextInt()
}
inner class MyBinder : Binder() {
fun getService(): BoundService = this@BoundService
}
}
这是我的主要活动
var boundService: BoundService? = null
var isBound = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
override fun onStart() {
super.onStart()
Intent(this, BoundService::class.java).also { intent ->
bindService(intent, boundServiceConnection, Context.BIND_AUTO_CREATE)
}
}
fun onButtonClick(v: View) {
if (isBound) {
val num: Int = boundService!!.randomGenerator()
Toast.makeText(this, "number: $num", Toast.LENGTH_LONG).show()
}
}
override fun onStop() {
super.onStop()
if (isBound) {
unbindService(boundServiceConnection)
isBound = false
}
}
private val boundServiceConnection: ServiceConnection = object : ServiceConnection {
override fun onServiceConnected(name: ComponentName, service: IBinder) {
val binderBridge = service as MyBinder
boundService = binderBridge.getService()
isBound = true
}
override fun onServiceDisconnected(name: ComponentName) {
isBound = false
boundService = null
}
}
关于应用程序的服务组件,应该在应用程序清单中注册
似乎没有提供有关所需(假设缺失)清单条目的任何信息,因为它在中有介绍。您说得对!我错过了那部分。多谢各位