15-1 서비스 이해하기

StrayCat·2022년 12월 9일
0

서비스

  • 오래 걸리는 작업을 백그라운드에서 처리할 수 있게 해주는 컴포넌트이다.
class MyService : Service(){
    override fun onBind(p0: Intent?): IBinder? {
        
    }
}
        <service android:name=".MyService"
            android:enabled="true"
            android:exported="true">
            
        </service>

  • 서비스를 실행하려면 startService() 와 bindService() 두가지로 시스템에 인텐트를 전달해야한다.

startService()

  • 명시적 인텐트
        val intent = Intent(this, MyService::class.java)
        startService(intent)
  • 암시적 인텐트
        val intent = Intent("ACTION_OUTER_SERVICE")
        intent.setPackage("com.example.test_outter")
        startService(intent)
  • 서비스 종료용
stopService(intent)

bindService()

  • bindService() 로 실행할 경우 ServiceConnection 인터페이스를 구현한 객체를 사용한다.
        val connection: ServiceConnection = object : ServiceConnection{
            override fun onServiceConnected(p0: ComponentName?, p1: IBinder?) {
                
            } // bindService() 시 자동 호출

            override fun onServiceDisconnected(p0: ComponentName?) {
                
            } // unbindService() 시 자동 호출

        }
  • bindService() 호출
  • 세번 째 매개변수는 Int타입의 flags로 BIND_AUTO_CREATE은 서비스가 실행상태가 아니어도 객체를 생성해서 실행하라는 의미이다.
        val intent = Intent(this, MyService::class.java)
        bindService(intent, connection, Context.BIND_AUTO_CREATE)
  • 서비스 종료
	unbindService(connection)

서비스 생명 주기

  • Unbounded 의 경우 startService()에서 객체가 생성되면 onCreate() -> onStartCommand() 를 통해 실행된다.

  • 이후 startService()가 실행될 경우, onStartCommand() 만 다시 호출한다.

  • Bounded 의 경우 bindService()를 통해 객체를 생성하면 onCreate() -> onBind() 가 실행 된다.

  • 이후 bindService() 를 실행할 경우 onBind() 만 다시 호출된다.

0개의 댓글