개요
- System에 의해 중단될 염려 X
- 상태 표시줄에 알림을 제공해야함.
- 권한 필요 (자동 부여) - android.permission.FOREGROUND_SERVICE
실행 요청 및 알림 == startForeground() / 중단 == stopForeground()
ex) Music Player
1편에서 살펴봤던 예제는 모두 앱을 종료시키면 (뒤로가기 2회클릭시) 음악이 꺼졌다.
[Android] Service <-> Activity Communication (feat. Bind Service)
Service는 App의 Background Thread로 동작한다고 소개했다. activity에서 어떤 버튼을 눌러 Service에게 Intent를 매개로 데이터를 넘겨주는 것(Activity -> Service)은 쉬웠다. 그럼 반대로 Service ->Activity..
m-falcon.tistory.com
Foreground Service는 앱을 종료해도 Background에 살아있다.
사용 방법
1. AndroidManifest에 포그라운드 권한등록

2. notification 객체, 빌더 생성
Foreground Service는 Notification이 필수이다.
아래와 같은 형태로 notification 객체를 생성한다.
val notificationId = 1000
val channel = NotificationChannel("channelMP3", "MusicPlayer", NotificationManager.IMPORTANCE_DEFAULT)
manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
manager?.createNotificationChannel(channel)
val builder = NotificationCompat.Builder(this, "channelMP3")
.setSmallIcon(R.drawable.ic_baseline_music_video_24)
.setContentTitle("MP3")
.setContentText("Music Playing~~")
val notification = builder.build()
3. Foreground 등록
startForeground 메소드로 등록
startForeground(notificationId, notification)
4. 등록 해제
stopForeground(true) -> Boolean parameter는 notification 제거 여부를 의미한다.
'Android' 카테고리의 다른 글
| [Android] SharedPreference (0) | 2020.07.03 |
|---|---|
| [Android] instance (0) | 2020.07.03 |
| [Android] Service <-> Activity Communication (feat. Bind Service) (0) | 2020.06.21 |
| [Android] Service (feat. Thread) (0) | 2020.06.20 |
| [Android] drawable resize, customizing (0) | 2020.06.20 |