728x90
Service는 백그라운드에서 오래 실행되는 작업을 수행할 수 있는 어플리케이션 구성 요소이다.
음악을 재생하거나 파일 I/O를 수행하는 등 콘텐츠 제공자와의 상호작용을 백그라운드에서 수행할 수 있다.
Foreground service 권한 요청
Android 9 (API level 28) 이상을 타깃으로 하는 앱은 반드시 FOREGROUND_SERVICE 권한을 요청해야한다. 이 권한은 중요도가 낮기 때문에 따로 사용자에게 요구할 필요 없이 자동으로 부여된다.
<manifest xmlns:android="http://schemas.android.com/apk/res/android" ...>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
<application ...>
...
</application>
</manifest>
Foreground service 시작
서비스를 실행하도록 인텐트에 담아 요청한다.
Kotlin Code
Kotlin Code
val intent = Intent(...) // 서비스 인텐트
startForegroundService(intent)
startForegroundService를 통해 서비스가 실행되면 바로 startForeground() 메소드를 호출해야한다. 이 메소드는 Notification 을 띄움으로써 사용자에게 서비스가 실행되고 있음을 알려준다.
Kotlin Code
Kotlin Code
val notification: Notification = Notification.Builder(this, CHANNEL_DEFAULT_IMPORTANCE)
.setContentTitle(getText(R.string.notification_title)) //알림 제목
.setContentText(getText(R.string.notification_message)) //알림 내용
.setSmallIcon(R.drawable.icon) //알림 아이콘
.build()
// Notification ID는 0이 될 수 없다.
startForeground(ONGOING_NOTIFICATION_ID, notification)
Java Code
Java Code
Notification notification =
new Notification.Builder(this, CHANNEL_DEFAULT_IMPORTANCE)
.setContentTitle(getText(R.string.notification_title)) // 알림 제목
.setContentText(getText(R.string.notification_message)) // 알림 내용
.setSmallIcon(R.drawable.icon) // 알림 아이콘
.build();
// Notification ID는 0이 될 수 없다.
startForeground(ONGOING_NOTIFICATION_ID, notification);
이 때 Android 8 (API26) 이상을 타겟하는 경우라면 Notification을 띄우기 전에 Notification을 채널에 할당해야 한다.
Kotlin Code
더보기
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// 채널 이름, 설명, 중요도 설정
val name = getString(R.string.channel_name)
val descriptionText = getString(R.string.channel_description)
val importance = NotificationManager.IMPORTANCE_DEFAULT
// 채널 생성
val mChannel = NotificationChannel(CHANNEL_ID, name, importance)
mChannel.description = descriptionText // 사용자에게 표시되는 설명글
val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(mChannel)
}
Java Code
더보기
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//채널 이름, 설명, 중요도 설정
CharSequence name = getString(R.string.channel_name);
String description = getString(R.string.channel_description);
int importance = NotificationManager.IMPORTANCE_DEFAULT;
// 채널 생성
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
channel.setDescription(description);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
중요도 수준 설정
채널 중요도는 아래 표시된 대로 사용자가 볼 수 있는 종요도 옵션을 설정한다.
사용자가 볼 수 있는 중요도 수준 | Android 8 이상 | Android 7.1 이하 |
긴급 알림음이 울리며 헤드업 알림으로 표시 |
IMPORTANCE_HIGH | PRIORITY_HIGH 또는 PRIORITY_MAX |
높음 알림음이 울림 |
IMPORTANCE_DEFAULT | PRIORITY_DEFAULT |
중간 알림음이 없음 |
IMPORTANCE_LOW | PRIORITY_LOW |
낮음 알림음이 없고 상태 표시줄에 표시 안됨 |
IMPORTANCE_MIN | PRIORITY_MIN |
728x90
반응형
댓글