안드로이드 앱 런처에 알림 개수 표시하기
이 예제는 안드로이드 앱의 런처(홈 화면) 아이콘에 알림 개수를 배지 형태로 표시하는 방법을 다룹니다. NotificationCompat.Builder의 setNumber()와 setBadgeIconType()을 활용하면 알림이 생성될 때마다 숫자가 누적되어 런처 아이콘 위에 표시됩니다. 참고로 배지 표시 여부는 기기 제조사의 런처(삼성, LG 등)가 배지 기능을 지원하는지에 따라 달라질 수 있습니다.
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: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:onClick = "createNotification" android:text = "create notification" android:layout_centerInParent = "true" android:layout_width = "match_parent" android:layout_height = "wrap_content" /> </RelativeLayout>
3단계 − MainActivity 코드 추가
src/MainActivity.java 파일에 아래 코드를 추가합니다.
package com.app.sample;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.app.NotificationChannel ;
import android.app.NotificationManager ;
import android.app.PendingIntent ;
import android.content.Intent ;
import android.os.Bundle ;
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);
}
@SuppressLint("WrongConstant")
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()) ;
}
}
4단계 − 매니페스트 코드 추가
Manifests/AndroidManifest.xml 파일에 아래 코드를 추가합니다.
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="https://schemas.android.com/apk/res/android" package="com.app.sample"> <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>
코드 핵심 포인트
- count 변수 − 버튼을 누를 때마다 1씩 증가하며 알림 개수를 추적합니다.
- onResume() − 사용자가 앱을 다시 열면 count를 0으로 초기화하여, 알림을 확인했다는 의미를 반영합니다.
- setNumber(count) − 런처 배지에 표시될 숫자를 지정합니다.
- setBadgeIconType(BADGE_ICON_SMALL) − 배지에 사용할 아이콘 유형을 지정합니다.
- 알림 채널 − Android 8.0(API 26, Oreo) 이상에서는 알림 채널을 생성해야 알림이 정상적으로 표시됩니다.
앱 실행 및 결과 확인
이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 모바일 기기가 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤 툴바의 Run 아이콘을 클릭하고, 실행 옵션에서 모바일 기기를 선택하세요. 그러면 기기에 아래와 같은 기본 화면이 표시됩니다.

