이 글은 『Do it! 깡샘의 안드로이드 앱 프로그래밍 with 코틀린』 교재를 바탕으로 작성되었습니다.
class MyService : Service() {
override fun onBind(intent: Intent): IBinder? {
return null
}
}
onBind()
는 서비스 컴포넌트의 필수 생명주기 함수<service
android:name=".MyService"
android:enabled="true"
android:exported="true"></service>
서비스 실행
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()
활용.서비스 종료
val intent = Intent(this, MyService::class.java)
stopService(intent)
class MyService : Service() {
override fun onBind(intent: Intent): IBinder? {
return null
}
}
onBind()
는 서비스 컴포넌트의 필수 생명주기 함수<service
android:name=".MyService"
android:enabled="true"
android:exported="true"></service>
val connection: ServiceConnection = object: ServiceConnection {
override fun onServiceConnected(name: ComponentName?, service: IBinder?) {}
override fun onServiceDisconnected(name: ComponentName?) {}
}
onServiceConnected()
는 bindService()
함수로 서비스를 구동할 때 자동으로 호출됨.onServiceDisconnected()
는 unbindService()
함수로 서비스를 종료할 때 자동으로 호출된다.서비스 실행
1) 명시적 인텐트로 실행
val intent = Intent(this, MyService::class.java)
bindService(intent, connection, Context.BIND_AUTO_CREATE)
bindService()
의 세 번째 매개변수는 Int타입의 flagContext.BIND_AUTO_CREATE
는 서비스가 실행 상태가 아니더라도 객체를 생성해서 실행하라는 의미이다. 2) 암시적 인텐트로 실행
val intent = Intent("ACTION_OUTER_SERVICE")
intent.setPackage("com.example.test_outer")
bindService(intent, connection, Context.BIND_aUTO_CREATE)
setPackage()
활용.서비스 종료
unbindService(connection)