
onBind() 함수는 필수startService(), 서비스와 액티비티 상호작용해야 한다면 bindService()val intent = Intent("ACTION_OUTER_SERVICE")
intent.setPackage(com.example.test_outer")
startService(intent)
val intent = Intent(this, MyService::class.java)
stopService(intent)
인텐트, serviceConnection 객체, 플래그)로 사용해야 하므로 두번째 매개변수 객체를 준비해야한다.val connection: ServiceConnection = object : ServiceConnection {
override fun onServiceConnected(name: ComponentName?, service: IBonder?){}
override fun onServiceDisconnected(name: ComponentName?){}
}
val intent = Intent(this, MyService::class.java)
bindService(intent, connection, Context.BIND_AUTO_CREATE)
Context.BIND_AUTO_CREATE 사용한다. 서비스가 실행 상태 아니더라도 객체 생성해서 실행하라는 뜻!unbindService(connection)으로 서비스 종료할 수 있음.IBinder 인터페이스이다. class MyBinder : Binder(){
fun funA(arg: Int){
}
fun funB(arg : Int){
return arg*arg
}
}
// 생명주기에서 onbind호출되고, IBinder타입 반환
override fun onBind(intent: Intent): IBinder? {
return MyBinder()
}
onServiceConnected 함수(bindService() 될 때 자동호출!!!)로 받을 수 있다. val connection: ServiceConnection = object : ServiceConnection {
// 아까 위에서 재정의해줘야 한다는 부분! 자동호출되며 서비스바인더 설정
override fun onServiceConnected(name: ComponentName?, service: IBinder?){
serviceBinder = service as MyService.MyBinder
}
override fun onServiceDisconnected(name: ComponentName?){//...재정의 필요...//}
}
...
// 이런 식으로 사용
serviceBinder.funA(10)
그냥 intent.putExtra 쓰면 안되나?
- 데이터 주고받을 때 엑스트라 데이터를 사용하면 되지 않나.싶지만 이는 인텐트로 특정 컴포넌트를 실행할 때 전달해야하는 데이터를 의미한다. 반면, 바인드 서비스는 인텐트로 이미 서비스가 실행된 상태에서 발생하는 데이터를 주고받는 방법이다.
서비스 실행한 곳에서는 IBinder 객체를 바인딩할 수도 있지만, API에서 제공하는 Messenger 객체를 바인딩 할 수도 있다.
요건 다음 시간에..일단 지금은 출근을 위해 자야함 ㅜ.ㅜ
그럼 20000