[Android][study] 서비스 컴포넌트 - 1

Intelli·2022년 11월 29일
0

이 글은 『Do it! 깡샘의 안드로이드 앱 프로그래밍 with 코틀린』 교재를 바탕으로 작성되었습니다.

15 - 1 서비스 이해하기


1. 서비스 생성과 실행

🍉 1. startService() 함수로 서비스 실행

  1. 서비스 컴포넌트 생성
class MyService : Service() {
	override fun onBind(intent: Intent): IBinder? {
    	return null
    }
}
  • onBind()는 서비스 컴포넌트의 필수 생명주기 함수
  1. 서비스 컴포넌트 등록
<service
	android:name=".MyService"
    android:enabled="true"
    android:exported="true"></service>
  1. 서비스 실행

    1) 명시적 인텐트로 실행

    val intent = Intent(this, MyService::class.java)
    startService(intent)

    2) 암시적 인텐트로 실행

    val intent = Intent("ACTION_OUTER_SERVICE")
    intent.setPackage("com.example.test_outer")
    startService(intent)
    • 암시적 인텐트로 인텐트 객체 생성
    • 외부 앱의 서비스를 이용하는 경우에 setPackage() 활용.
  2. 서비스 종료

val intent = Intent(this, MyService::class.java)
stopService(intent)

🍎 2. bindService() 함수로 서비스 실행

  1. 서비스 컴포넌트 생성
class MyService : Service() {
	override fun onBind(intent: Intent): IBinder? {
    	return null
    }
}
  • onBind()는 서비스 컴포넌트의 필수 생명주기 함수
  1. 서비스 컴포넌트 등록
<service
	android:name=".MyService"
    android:enabled="true"
    android:exported="true"></service>
  1. ServiceConnection 인터페이스 구현
val connection: ServiceConnection = object: ServiceConnection {
	override fun onServiceConnected(name: ComponentName?, service: IBinder?) {}
    override fun onServiceDisconnected(name: ComponentName?) {}
}
  • onServiceConnected()bindService() 함수로 서비스를 구동할 때 자동으로 호출됨.
  • onServiceDisconnected()unbindService() 함수로 서비스를 종료할 때 자동으로 호출된다.
  1. 서비스 실행

    1) 명시적 인텐트로 실행

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

    2) 암시적 인텐트로 실행

    val intent = Intent("ACTION_OUTER_SERVICE")
    intent.setPackage("com.example.test_outer")
    bindService(intent, connection, Context.BIND_aUTO_CREATE)
    • 암시적 인텐트로 인텐트 객체 생성
    • 외부 앱의 서비스를 이용하는 경우에 setPackage() 활용.
  2. 서비스 종료

unbindService(connection)

2. 서비스 생명주기

profile
I never dreamed about success. I worked for it.

0개의 댓글