안드로이드에서 자동으로 사라지는 알림(Notification) 만들기
이 튜토리얼에서는 안드로이드에서 로컬 알림(Local Notification)을 생성하고, 사용자가 알림을 탭하면 알림창에서 스스로 사라지도록 만드는 방법을 단계별로 살펴봅니다.
핵심은 setAutoCancel(true) 메서드입니다. 이 옵션을 설정하면 사용자가 알림을 클릭하는 순간 해당 알림이 자동으로 제거되어, 별도의 삭제 처리 없이 깔끔한 사용자 경험을 제공할 수 있습니다.
1단계: 새 프로젝트 생성
Android Studio를 실행하고 File → New Project 메뉴로 이동한 후, 필요한 정보를 모두 입력하여 새 프로젝트를 생성합니다.
2단계: 레이아웃 파일 작성 (activity_main.xml)
res/layout/activity_main.xml 파일에 아래 코드를 추가합니다. 화면 중앙에 'Create Notification' 버튼 하나를 배치하는 간단한 구조입니다.
<?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:id="@+id/btnCreateNotification"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentEnd="true"
android:layout_centerInParent="true"
android:text="Create Notification" />
</RelativeLayout>3단계: MainActivity에 알림 생성 코드 추가
src/MainActivity.java 파일에 다음 코드를 추가합니다. 버튼을 클릭하면 알림이 생성되며, setAutoCancel(true) 덕분에 사용자가 알림을 탭하면 자동으로 사라집니다.
package app.tutorialspoint.com.notifyme;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
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);
}
public void createNotification(View view) {
NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(MainActivity.this, default_notification_channel_id);
mBuilder.setContentTitle("My Notification");
mBuilder.setContentText("Notification Listener Service Example");
mBuilder.setTicker("Notification Listener Service Example");
mBuilder.setSmallIcon(R.drawable.ic_launcher_foreground);
mBuilder.setAutoCancel(true); // 알림 탭 시 자동 삭제
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());
}
}주요 코드 설명
- setAutoCancel(true): 사용자가 알림을 탭하면 알림창에서 자동으로 제거되도록 설정합니다. 이 예제의 핵심 부분입니다.
- NotificationChannel: 안드로이드 8.0(Oreo, API 26) 이상에서는 반드시 알림 채널을 생성해야 알림이 정상적으로 표시됩니다.
- notify() 메서드: 고유한 알림 ID를 전달하여 알림을 발송합니다. 여기서는 현재 시간을 밀리초 단위로 변환해 ID 중복을 방지했습니다.
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">
<uses-permission android:name="android.permission.VIBRATE" />
<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 아이콘을 클릭하세요. 목록에서 본인의 모바일 기기를 선택하면, 기본 화면이 표시된 앱이 기기에서 실행됩니다.


'Create Notification' 버튼을 누르면 알림이 생성되고, 해당 알림을 탭하면 setAutoCancel(true) 옵션에 의해 알림이 자동으로 사라지는 것을 확인할 수 있습니다.