์๋๋ก์ด๋ ์ฑ์ ๊ฐ๋ฐํ๋ค ๋ณด๋ฉด,
๋ฐฑ๊ทธ๋ผ์ด๋์์๋ ๋๊ธฐ์ง ์๊ณ ์คํ๋์ด์ผ ํ๋ ์์
์ด ์์ด์.
์๋ฅผ ๋ค์ด:
์ด๋ด ๋ ์ฌ์ฉํ๋ ๊ฒ ๋ฐ๋ก ํฌ๊ทธ๋ผ์ด๋ ์๋น์ค(Foreground Service)์
๋๋ค.
์ค๋์ Foreground Service์ ๊ฐ๋
, ํน์ง, ๊ตฌํ ๋ฐฉ๋ฒ์ ์ ๋ฆฌํด ๋ณด๊ฒ ์ต๋๋ค. ๐
Foreground Service๋
์ฑ์ด ๋ฐฑ๊ทธ๋ผ์ด๋์ ์์ด๋ ์ค์ํ ์์
์ ์ค๋จ ์์ด ์คํํ ์ ์๊ฒ ํด์ฃผ๋ ์๋น์ค์์.
Service์ ๋ฌ๋ฆฌ,๐ ํต์ฌ:
์ค์ํ ์์
์ด ์คํ ์ค์์ ์ฌ์ฉ์์๊ฒ ์๋ฆฌ๊ณ , ์์คํ
์ ์ํด ์ฝ๊ฒ ์ข
๋ฃ๋์ง ์๋๋ก ๋ณด์ฅ
@AndroidEntryPoint
class MusicService : Service() {
private val channelId = "music_channel"
override fun onCreate() {
super.onCreate()
createNotificationChannel()
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
val notification = NotificationCompat.Builder(this, channelId)
.setContentTitle("๐ต ์์
์ฌ์ ์ค")
.setContentText("ํ์ฌ ๊ณก: Imagine - John Lennon")
.setSmallIcon(R.drawable.ic_music_note)
.build()
// Foreground Service ์์
startForeground(1, notification)
// ์ค์ ์คํํ ์์
(์: ์์
์ฌ์ ๋ก์ง)
return START_STICKY
}
override fun onBind(intent: Intent?): IBinder? = null
private fun createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(
channelId,
"Music Playback",
NotificationManager.IMPORTANCE_LOW
)
getSystemService(NotificationManager::class.java).createNotificationChannel(channel)
}
}
}
<service
android:name=".MusicService"
android:exported="false"
android:foregroundServiceType="mediaPlayback" />
foregroundServiceType โ ์ด๋ค ์ ํ์ ์์
์ธ์ง ๋ช
์ (location, mediaPlayback, dataSync ๋ฑ) val intent = Intent(context, MusicService::class.java)
ContextCompat.startForegroundService(context, intent)
FOREGROUND_SERVICE_PERMISSION) foregroundServiceType์ ๋ช
ํํ ์ง์ (๋ฏธ๋์ด/์์น/๋ฐ์ดํฐ ๋ฑ) ์ค๋์ Foreground Service์ ๋ํด ์ดํด๋ดค์ต๋๋ค.
foregroundServiceType ์ง์ ํ์ ๐ ๊ฒฐ๋ก :
Foreground Service๋ โ์ค์ํ ์คํ์ ์ฌ์ฉ์์๊ฒ ์๋ฆฌ๋ฉฐ ๋ณด์ฅํ๋ ์๋น์คโ์
๋๋ค. ๐