버그 잡이

android 백그라운드 음악 재생 어떤 service를 쓸 것인가? 본문

안드로이드/4대 구성요소

android 백그라운드 음악 재생 어떤 service를 쓸 것인가?

버그잡이 2020. 5. 6. 22:06

* 요구사항

 

1. 음악 재생이 2분 이상 지속될 수 있어야 한다.

2. 음악 재생 상태가 UI에 반영될 필요는 없다.

 

 

 

서비스를 시작하는 두가지 방법

 

 

서비스를 시작하는 방법에는 위와 같이 두 가지 방법이 있다.

 

startService()는 가장 기본적인 service 실행 방법이고

 

bindService()는 service와 activity가 서로 통신할 수 있게 해주는 기능이 있다.

ex) 음악 재생시 재생 상태에 따라 버튼 모양 변경

 

 

-> 내가 만들 앱은 알람앱으로 단순 음악만 재생하면 되기 때문에 startService()로 실행하겠다.

 

 

 

 

오레오 이후 백그라운드 서비스 제한

 

 

오레오 버전 이후 백그라운드에 대한 제한이 엄격해졌다.

어느 정도냐면 실제로 백그라운드에서 서비스를 실행하고 5초가 지나면 service가 자동 종료된다.

 

이를 해결하기 위해서는 백그라운드 서비스를 Foreground 서비스로 만들어줘야한다.

 

 

*Activity.kt

 

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_alarm_show)

      
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForegroundService(intentService)
        } else {
            startService(intentService)
        }
        
 }

 

- startForegroundService()는 Service 의 onCreate()를 호출하고

- startService()는 Service의 onStartCommand()를 호출한다.

 

*왜 이렇게 나눈지는 모르겠지만 내 뇌피셜로는 onStartCommand()에서 실행되는 친구들은 전부 5초간 제약을 주는 구조로 만들고 그 이상의 실행을 원하면 onCreate()에서 만들 것을 유도한게 아닐까 싶다.

 

 

 

*Service.kt

 

    override fun onCreate() {
        if (Build.VERSION.SDK_INT >= 26) {
            val CHANNEL_ID = "my_channel_01"
            val channel = NotificationChannel(
                CHANNEL_ID,
                "Channel human readable title",
                NotificationManager.IMPORTANCE_DEFAULT
            )

            (getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager).createNotificationChannel(channel)

			//foreground 설정을 위해선 notification이 필요하다
            val notification = NotificationCompat.Builder(this, CHANNEL_ID)
                .setContentTitle("")
                .setContentText("").build()

            startForeground(111, notification)

            mediaPlayer.start()
            Log.d("AlarmService : ", "음악이 시작됩니다..")

        }
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        return super.onStartCommand(intent, flags, startId)
        mediaPlayer.start()
        Log.d("AlarmService : ", "음악이 시작됩니다..")

    }

 

반응형
Comments