IntentService는 인텐트를 전달하여 서비스의 어떤 작업을 수행하는데 사용될 수 있습니다. 파일 다운로드나 업로드 등의 처리 시간이 긴 작업을 수행하는데 사용할 수 있습니다. 또한, 인텐트만 전달하면 되기 때문에 사용하기 간편합니다.
IntentService를 구현하고 사용하는 방법에 대해서 알아보겠습니다.
이 글의 코드는 kotlin으로 작성되었습니다.
IntentService는 background 제한 정책이 적용되면서 deprecated되었습니다. Android 8.0(API 26) 이상에서는 WorkManager나 JobIntentService를 이용할 수 있습니다.
구현
먼저 다음과 같이 IntentService를 상속하는 서비스를 생성합니다.
class MyIntentService : IntentService("MyIntentService") {
companion object {
const val TAG = "MyIntentService"
}
// 1
override fun onHandleIntent(intent: Intent?) {
Log.d(TAG, "MSG: ${intent?.getStringExtra("MSG")}")
for (i in 1..10) {
Thread.sleep(1000)
Log.d(TAG, "onHandleIntent() : $i")
}
}
// 2
override fun onDestroy() {
super.onDestroy()
Log.d(TAG, "Job execution finished")
}
}
- Intent가 전달되면
onHandleIntent()
가 callback되며 여기서 Job을 수행하도록 구현할 수 있습니다. - 모든 인텐트가 처리되면
onDestroy()
가 호출되며 서비스는 종료됩니다.
AndroidManifest.xml
에는 다음과 같이 Service를 선언합니다.
<service android:name=".MyIntentService" />
이렇게 코드를 작성하고 Manifest에 등록하면 서비스를 이용할 수 있습니다.
실행
다음과 같이 인텐트를 실행하고, startService()
로 서비스를 실행할 수 있습니다.
val intent = Intent(this, MyIntentService::class.java)
intent.putExtra("MSG", "Do something")
startService(intent)
위에서 말한 것처럼 Intent는 onHandleIntent()
로 전달됩니다.
위의 코드를 실행한 결과는 다음과 같습니다.
12-29 21:10:18.029 9734 9782 D MyIntentService: MSG: Do something
12-29 21:10:19.029 9734 9782 D MyIntentService: onHandleIntent() : 1
12-29 21:10:20.029 9734 9782 D MyIntentService: onHandleIntent() : 2
12-29 21:10:21.030 9734 9782 D MyIntentService: onHandleIntent() : 3
12-29 21:10:22.030 9734 9782 D MyIntentService: onHandleIntent() : 4
12-29 21:10:23.030 9734 9782 D MyIntentService: onHandleIntent() : 5
12-29 21:10:24.030 9734 9782 D MyIntentService: onHandleIntent() : 6
12-29 21:10:25.031 9734 9782 D MyIntentService: onHandleIntent() : 7
12-29 21:10:26.031 9734 9782 D MyIntentService: onHandleIntent() : 8
12-29 21:10:27.031 9734 9782 D MyIntentService: onHandleIntent() : 9
12-29 21:10:28.032 9734 9782 D MyIntentService: onHandleIntent() : 10
12-29 21:10:28.037 9734 9734 D MyIntentService: Job execution finished
이 글에서 사용한 예제는 GitHub에서 확인할 수 있습니다.
주의사항
Android Oreo부터 Background 서비스 실행을 제한합니다. IntentService가 Foreground에서만 실행된다면 문제없지만, App이 Background로 전환되면 Service가 중단되거나 실행되지 않을 수 있습니다. 이런 문제를 피하기 위해 WorkManager나 JobIntentService를 사용할 수 있습니다.
참고
Related Posts
- Android - 진동, Vibrator, VibrationEffect 예제
- Android - TabLayout 구현 방법 (+ ViewPager2)
- Android - PackageManager로 Package 정보 가져오기
- Android - ACTION_BOOT_COMPLETED 이벤트 받기
- Android - FusedLocationProviderClient으로 위치 정보 얻기
- Android - GPS, Network 위치 정보 얻기 (LocationManager)
- Android - Foreground Service 실행
- Android - 시간, 날짜 변경 이벤트 받기
- Android - currentTimeMillis(), elapsedRealtime(), uptimeMillis()
- Android - PowerManager WakeLock
- Android - 파일 입출력 예제 (Read, Write, 내부, 외부 저장소)
- Android - Screen On/Off 이벤트 수신, 상태 확인
- Android - 다른 앱의 Service에 바인딩
- Android - Handler vs Executor
- Android - Darkmode 활성화하는 방법
- Android - hasSystemFeature(), 지원되는 Feature 확인
- Android - 앱 권한 확인(Permission check)
- Android - 설치된 앱 리스트 가져오기
- Android App Shortcuts 구현
- Android - ContentProvider 구현 및 예제
- Android - AIDL을 이용하여 Remote Service 구현
- Android - Uri, Scheme, SSP(Scheme Specific Part) 정리
- Android - 앱 설치, 삭제 이벤트 받기 (BroadcastReceiver 인텐트 받기)
- Android - SharedPreferences로 간단한 데이터 저장 방법
- Android - AlarmManager로 알람을 등록하는 방법
- Android - Quick Settings에 Custom Tile 추가하는 방법 (kotlin)
- Android - Broadcast Receiver 등록 및 이벤트 수신 방법
- Android - 앱 권한 요청 (kotlin)
- Android - 네트워크(WIFI) 연결 상태 확인 및 변경 감지
- Mockito - static, final method를 mocking하는 방법
- Andriod - 커스텀 퍼미션을 정의하는 방법
- Robolectric으로 Unit Test 작성하기
- Android Mockito로 Unit 테스트 코드 작성하기 (kotlin)
- Android - Handler 사용 방법
- Android - IntentService 사용 방법
- Android - JobIntentService 사용 방법