이 튜토리얼에서는 Android 앱의 런처 아이콘에 알림 개수(배지)를 표시하는 방법을 단계별로 소개합니다. 알림이 도착할 때마다 홈 화면의 앱 아이콘 위에 숫자가 표시되도록 구현할 수 있습니다.
1단계: 새 프로젝트 생성
Android Studio에서 File → New Project를 선택하고, 프로젝트 생성에 필요한 모든 정보를 입력해 새 프로젝트를 만듭니다.
2단계: 레이아웃 작성
res/layout/activity_main.xml 파일에 아래 코드를 추가합니다. 화면 중앙에 알림을 생성하는 버튼 하나만 배치한 간단한 레이아웃입니다.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
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:onClick="createNotification"
android:text="알림 생성"
android:layout_centerInParent="true"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</RelativeLayout>
3단계: MainActivity 구현
src/MainActivity.java 파일에 아래 코드를 추가합니다.
package app.tutorialspoint.com.notifyme;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import static android.app.Notification.BADGE_ICON_SMALL;
public class MainActivity extends AppCompatActivity {
static int count = 0;
public static final String NOTIFICATION_CHANNEL_ID = "10001";
private final static String default_notification_channel_id = "default";
@Override
protected void onResume() {
super.onResume();
count = 0; // 앱을 열면 배지 카운트 초기화
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void createNotification(View view) {
count++;
Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);
notificationIntent.putExtra("fromNotification", true);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext(), default_notification_channel_id);
mBuilder.setContentTitle("My Notification");
mBuilder.setContentIntent(pendingIntent);
mBuilder.setContentText("Notification Listener Service Example");
mBuilder.setSmallIcon(R.drawable.ic_launcher_foreground);
mBuilder.setAutoCancel(true);
mBuilder.setBadgeIconType(BADGE_ICON_SMALL);
mBuilder.setNumber(count); // 런처 아이콘에 표시될 알림 개수
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());
}
}
코드의 핵심 요소는 다음과 같습니다.
setBadgeIconType(BADGE_ICON_SMALL)— 배지 아이콘의 형태를 지정합니다.setNumber(count)— 런처 아이콘에 표시할 알림 개수를 설정합니다. 버튼을 누를 때마다 count 값이 증가합니다.onResume()에서 count를 0으로 초기화해, 앱을 열면 배지 숫자가 사라지도록 처리했습니다.- Android 8.0(오레오, API 26) 이상에서는
NotificationChannel을 먼저 생성해야 알림이 정상적으로 표시됩니다.
4단계: 매니페스트 설정
AndroidManifest.xml 파일에 아래 코드를 추가합니다.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="app.tutorialspoint.com.notifyme">
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<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 기기를 컴퓨터에 연결했다고 가정하고 앱을 실행해 보겠습니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바의 Run 아이콘을 클릭하세요. 옵션 목록에서 사용 중인 모바일 기기를 선택하면 기기에 기본 화면이 나타납니다. 버튼을 누를 때마다 알림이 발생하고, 홈 화면의 앱 아이콘에는 누적된 알림 개수가 배지로 표시됩니다.

참고 사항
런처 배지 표시 여부는 기기 제조사의 런처 앱에 따라 달라질 수 있습니다. 삼성, LG 등 대부분의 주요 제조사 런처는 setNumber() 값을 지원하지만, 일부 순정 안드로이드 런처에서는 배지가 표시되지 않을 수 있습니다. 또한 위 코드는 하위 버전 호환을 위해 안드로이드 서포트 라이브러리(android.support)를 사용하고 있으므로, 최신 프로젝트라면 AndroidX(androidx.appcompat.app.AppCompatActivity, androidx.core.app.NotificationCompat)로 마이그레이션하는 것을 권장합니다.