안드로이드 학습(Kotlin)

22. Foreground Service를 활용한 음악 재생

리저브콜드브루 2025. 2. 10. 11:12
728x90
반응형
 

3. Android 4대 컴포넌트 (Activity, Service, BroadcastReceiver, ContentProvider)의 이해

Andoird의 4대 컴포넌트는 앱의 구조와 실행 흐름을 결정하는 핵심 요소다.각 컴포넌트는 독립적으로 동작하면서도 서로 상호작용하며 앱의 기능을 구성한다.Activity (화면 구성 컴포넌트)UI를 포함

joyshu93.tistory.com

 

Service의 유형

유형 설명
Foreground Service 사용자에게 지속적으로 표시되며, Notification을 필수로 포함해야 함
Background Service UI 없이 실행되며 일정 시간이 지나면 시스템이 자동 종료
Bound Service 서비스가 종료될 때 호출

 

 

Foreground Service

  • 앱이 종료되더라도 지속적으로 실행 가능
  • 음악 재생, 다운로드, 위치 서비스 등 활용
  • 백그라운드 실행이지만 알림(Notification)을 통해 사용자에게 표시됨

음악 재생 예제

Foreground Service를 사용해 음악을 백그라운드에서 재생

 

클래스 생성 (MusicService)

class MusicService : Service() {

    private lateinit var mediaPlayer: MediaPlayer // 객체 선언

    override fun onCreate() {
        super.onCreate()
        
        // MediaPlayer 초기화 및 음악 파일 로드
        mediaPlayer = MediaPlayer.create(this, R.raw.sample_music)
        mediaPlayer.isLooping = true // 반복 재생 설정
    }

	// 서비스 시작 시 호출되는 함수 (음악 재생 시작)
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        startForeground(1, createNotification()) // Foreground Service 시작, 알림과 함께 실행
        mediaPlayer.start() // 음악 재생
        
        // START_STICKY: 서비스가 강제로 종료되면 시스템에서 자동으로 다시 시작
        return START_STICKY
    }

	// 서비스 종료 시 호출되는 함수 (자원 해제)
    override fun onDestroy() {
        super.onDestroy()
        mediaPlayer.stop() //음악 재생 중단
        mediaPlayer.release() //MediaPlayer 자원 해제
    }

    override fun onBind(intent: Intent?): IBinder? = null

    private fun createNotification(): Notification {
        val channelId = "music_service_channel"
        
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                channelId, "Music Service",
                NotificationManager.IMPORTANCE_LOW // 알림 중요도 낮음(백그라운드 작업 알림)
            )
            val manager = getSystemService(NotificationManager::class.java)
            manager.createNotificationChannel(channel)
        }
        
        // 알림 생성 및 반환
        return NotificationCompat.Builder(this, channelId)
            .setContentTitle("음악 재생 중") // 알림 제목
            .setContentText("백그라운드에서 음악을 재생합니다.") // 알림 내용
            .setSmallIcon(R.drawable.ic_music) // 알림 아이콘
            .build()
    }
}

 

 

onStartCommand 반환 값

  • START_STICKY
    • 강제 종료 시 자동으로 서비스 재생성
    • 서비스가 항상 실행되어야 하고, 중단되면 재생성되어야 하는 경우
    • 음악 재생 서비스에 적합
  • START_NOT_STICKY
    • 강제 종료 시 다시 시작하지 않음
    • 작업이 일회성이고 중단되면 다시 시작할 필요가 없는 경우
    • 다운로드 서비스에 적합
  • START_REDELIVER_INTENT
    • 강제 종료 시 다시 시작하고 마지막 Intent를 다시 전달
    • 중단된 작업을 이어서 처리해야하 하는 경우
    • 데이터 업로드 서비스에 적합

 

서비스 실행 및 종료

음악 재생 시작

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

 

음악 재생 중지

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

 

 

AndroidManifest.xml에 서비스 등록

<service
    android:name=".MusicService"
    android:foregroundServiceType="media"
    android:exported="false"/>

 

728x90
반응형