이것저것 공부한 기록

[Android] Foreground Service App 만들기 본문

Study/Kotlin&Android

[Android] Foreground Service App 만들기

블랜디 2023. 5. 8. 16:41

1. Android Studio - New - Empty Project 생성

 

2. Service 생성

 

3. Service를 실행해 줄 Default Activity 생성

 

4. Manifest 수정

- FOREGROUND_SERVICE permission 추가

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

- Application 객체 생성할 시 Manifest의 Application name 지정

<application
        android:name=".aaPersonalApplication
        ...
        >

- Application 내 Activity, Service 추가

<application>
	<activity
            android:name=".AppStartActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>


        <service
            android:name=".aaService"
            android:configChanges="locale" />
</application>

 

5. Service 실행

- Notification 채널 등록 및 StartForeground()호출 해줘야 함

        val CHANNEL_ID = "aaa_service_channel"

        val notificationChannel = NotificationChannel(CHANNEL_ID, "aaa Application",
            NotificationManager.IMPORTANCE_LOW)
        val nm = getSystemService(NotificationManager::class.java)
        nm.createNotificationChannel(notificationChannel)

        val notification = Notification.Builder(this, CHANNEL_ID)
            .setContentTitle("aaa Service")
            .setContentText("aaa service is running")
            .build()
        
        startForeground(STOP_FOREGROUND_REMOVE, notification)

 

* android.app.ForegroundServiceDidNotStartInTimeException

- 안드로이드 12 Targeting application에서 앱 실행 후 포그라운드로 올라오지 못해서 발생하는 Exception

- StartForegroundService로 호출된 Service의 경우 Service 내부에서 StartForeground()를 호출해줘야 함