모바일 앱(안드로이드)

Android Foreground Services 사용법

Billcorea 2024. 10. 17. 15:45
반응형

Android Foreground Services 사용법

good job

 

안녕하세요! 이번 포스트에서는 Android Foreground Services에 대해 알아보겠습니다. Foreground Service는 사용자가 앱과 상호작용하지 않더라도 백그라운드에서 지속적으로 실행되어야 하는 작업을 수행하는  사용됩니다. 아래는 Foreground Service 설정 방법에 대한 자세한 설명입니다.

1. 서비스 클래스 생성

먼저 Service를 상속받는 서비스 클래스를 정의합니다.

kotlin
class MyForegroundService : Service() {
    private lateinit var notification: Notification

    override fun onCreate() {
        super.onCreate()
        startForeground(1, createNotification())
    }

    private fun createNotification(): Notification {
        val builder = NotificationCompat.Builder(this, "channel_id")
            .setContentTitle("Foreground Service")
            .setContentText("This is a foreground service")
            .setSmallIcon(R.drawable.ic_launcher_foreground)
            .setContentIntent(PendingIntent.getActivity(this, 0, Intent(this, MainActivity::class.java), 0))
            .setAutoCancel(false)
        
        // android api 26 이상의 경우 필요
        val channel = NotificationChannel("channel_id", "Channel Name", NotificationManager.IMPORTANCE_DEFAULT)
        val notificationManager = getSystemService(NotificationManager::class.java)
        notificationManager.createNotificationChannel(channel)
        
        return builder.build()
    }

    override fun onBind(intent: Intent): IBinder? {
        return null
    }

    override fun onDestroy() {
        super.onDestroy()
        stopForeground(true)
    }
}

2. 서비스 시작

서비스를 시작하려면 액티비티나 프래그먼트에서 다음과 같이 호출합니다.

kotlin
val serviceIntent = Intent(this, MyForegroundService::class.java)
// android api 30 이상의 경우 
startForegroundService(serviceIntent)

3. AndroidManifest.xml 설정

AndroidManifest.xml 파일에 서비스 선언을 추가합니다.

xml
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_CONNECTED_DEVICE" />

<application 
...

<service
    android:name=".MyForegroundService"
    android:exported="false"
    android:foregroundServiceType="connectedDevice"
    />
</application>

4. Notification Channel 생성

앱이 Android Oreo(API 레벨 26) 이상을 타겟으로 하는 경우, Notification Channel을 생성해야 합니다.

kotlin
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    val channel = NotificationChannel("channel_id", "Channel Name", NotificationManager.IMPORTANCE_DEFAULT)
    val notificationManager = getSystemService(NotificationManager::class.java)
    notificationManager.createNotificationChannel(channel)
}

5. Deprecated 메서드 대체

stopForeground 메서드가 deprecated 되었기 때문에, 대신 stopSelf 또는 stopService 메서드를 사용합니다.

kotlin
override fun onDestroy() {
    super.onDestroy()
    stopSelf()
}

6. 안드로이드 생명 주기와 서비스 관리

적절한 시점에 startService와 stopService를 호출하여 서비스의 시작과 종료를 관리해야 합니다. 예를 들어:

  • onCreate() 또는 onStart(): 앱이 처음 실행될 때.
  • onDestroy(): 앱이 종료될 때.

 포스트가 Android Foreground Services 설정과 관리에 도움이 되길 바랍니다. 궁금한 점이 있으면 언제든지 댓글로 남겨주세요! 😊



반응형