Foreground + bind?

안드로이드 공식 페이지에서 서비스 관련 내용을 읽다, 흥미로운 내용을 발견했다.

서비스 생명 주기 관리에서 startService()bindService() 로 생성된 서비스(포그라운드)와 바인드 서비스는 완전히 별개가 아니다. 음악 재생 플레이어의 경우 startService()를 통해 서비스를 생성 후, 사용자가 더 많은 통제력을 발휘하려고 하거나, 현재 노래에 대한 정보를 얻고자 할 때, Activity가 bindService() 를 호출하여 바인드 할 수 있다.

직접 코드 구현을 통해, 몇가지 상황을 테스트 해보려고 한다.

테스트 어플리케이션

서비스에서 두가지 스톱워치를 실행하여, 서비스의 상태를 확인하고자 한다.

  1. Foreground 서비스 전용 스톱워치
  2. Bind 서비스 전용 스톱워치

Screenshot_1641490413.png

MainActivity

서비스 실행 & 종료

서비스의 실행은 버전에 맞춰 startForegroundService() 혹은 startService() 로 실행한다.

private fun startMyService() {
    val intent = Intent(this, MyService::class.java)
    if (Build.VERSION.SDK_INT>= 26) {
        startForegroundService(intent)
    } else {
        startService(intent)
    }
}

private fun endMyService() {
        val intent = Intent(this, MyService::class.java)
        stopService(intent)
}

서비스 Connection

서비스 Binding을 위해, 서비스와의 연결을 모니터링하는 ServiceConnection을 반드시 구현해야 한다.

서비스와의 연결이 끊어지면 자동으로 Bind를 해제하도록 한다.

서비스가 연결되면, Bind하고 플래그(isServiceBound) 값을 바꿔준다.

private val connection = object : ServiceConnection {
    override fun onServiceDisconnected(name: ComponentName?) {
        Log.d("MyService", "onServiceDisconnected 호출")
        unbindMyService()
    }

    override fun onServiceConnected(name: ComponentName?, binder: IBinder?) {
        Log.d("MyService", "onServiceConnected 호출")
        val binder = binder as MyService.MyBinder
        service = binder.getService()
        isServiceBound = true
    }
}

서비스 Bind&Unbind

Bind 서비스 FLAG