메신저 앱을 사용하다 보면 여러 개의 메시지가 도착할 때 각각의 알림이 쌓이는 것이 아니라 하나의 그룹으로 묶여 표시되는 것을 본 적이 있을 것입니다. WhatsApp이 대표적인 예로, 여러 채팅 알림이 하나로 정리되어 사용자 경험을 크게 향상시킵니다.
이번 튜토리얼에서는 NotificationCompat.InboxStyle과 고유한 알림 ID를 활용해 안드로이드에서 이러한 알림 그룹화 기능을 구현하는 방법을 단계별로 살펴보겠습니다.
사전 준비 사항
알림 그룹화를 구현하려면 다음 두 가지 핵심 요소를 이해해야 합니다.
- 고유한 알림 ID: 각 알림마다 서로 다른 ID를 부여해야 시스템이 알림들을 개별적으로 인식하고 그룹에 추가할 수 있습니다.
- InboxStyle: 여러 줄의 텍스트를 펼쳐진 형태로 표시할 수 있는 스타일로, 그룹화된 알림에 적합합니다.
1단계 — 새 프로젝트 생성
Android Studio를 실행하고 File → New Project 메뉴로 이동한 뒤, 새 프로젝트 생성에 필요한 모든 세부 정보를 입력하여 프로젝트를 만듭니다.
2단계 — activity_main.xml 레이아웃 작성
res/layout/activity_main.xml 파일에 아래 코드를 추가합니다. 화면 중앙에 알림을 생성하는 버튼 하나를 배치하는 구성입니다.
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:app="https://schemas.android.com/apk/res-auto"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
tools:context=".MainActivity">
<Button
android:id="@+id/btnCreateNotification"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Create notification"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
</android.support.constraint.ConstraintLayout>3단계 — MainActivity.java 구현
src/MainActivity.java 파일에 아래 코드를 추가합니다. 버튼을 클릭할 때마다 새로운 알림이 발생하며, System.currentTimeMillis() 값을 ID로 사용하기 때문에 매번 고유한 알림이 생성되어 자동으로 그룹에 쌓이게 됩니다.
package app.tutorialspoint.com.notifyme;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
public static final String NOTIFICATION_CHANNEL_ID = "10001";
private final static String default_notification_channel_id = "default";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnCreateNotification = findViewById(R.id.btnCreateNotification);
btnCreateNotification.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(MainActivity.this,
default_notification_channel_id)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("Test")
.setStyle(new NotificationCompat.InboxStyle())
.setContentText("Hello! This is my first push notification");
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel notificationChannel =
new NotificationChannel(NOTIFICATION_CHANNEL_ID,
"NOTIFICATION_CHANNEL_NAME", importance);
mBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
assert mNotificationManager != null;
mNotificationManager.createNotificationChannel(notificationChannel);
}
assert mNotificationManager != null;
mNotificationManager.notify((int) System.currentTimeMillis(),
mBuilder.build());
}
});
}
}핵심 포인트
- setStyle(InboxStyle): 알림이 확장될 때 여러 줄의 내용을 받은편지함 형태로 표시합니다.
- notify()에 동적 ID 전달: 버튼을 누를 때마다 현재 시간 기반의 새 ID가 할당되므로, 기존 알림을 덮어쓰지 않고 계속 추가됩니다.
- 알림 채널 처리: 안드로이드 8.0(오레오) 이상에서는 반드시 알림 채널을 생성해야 하므로 SDK 버전을 확인하는 조건문이 포함되어 있습니다.
4단계 — AndroidManifest.xml 설정
androidManifest.xml 파일에 아래 코드를 추가합니다.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="app.tutorialspoint.com.notifyme">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>앱 실행 및 결과 확인
이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 기기가 컴퓨터와 연결되어 있다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 후, 툴바의 Run 아이콘을 클릭하세요. 실행 옵션 목록에서 자신의 모바일 기기를 선택하면, 기기 화면에 아래와 같은 기본 화면이 표시됩니다.

버튼을 여러 번 클릭하면 알림이 하나씩 추가되며, 상태 바를 펼치면 여러 알림이 InboxStyle 형태로 함께 표시되는 것을 확인할 수 있습니다. 이 방식을 응용하면 WhatsApp처럼 채팅 메시지나 이메일 등 다양한 유형의 알림을 깔끔하게 그룹화할 수 있습니다.