안드로이드 앱을 개발하다 보면 사용자가 알림을 탭한 후에도 알림이 알림창에 그대로 남아 있어야 하는 경우가 있습니다. 진행 중인 작업의 상태를 계속 표시하거나, 사용자가 반복해서 확인해야 하는 정보를 담은 알림이 대표적인 예입니다.
기본적으로 알림을 클릭하면 자동으로 사라지지만, NotificationCompat.Builder의 setAutoCancel(false) 옵션을 사용하면 클릭 후에도 알림이 유지됩니다. 이 글에서는 알림을 클릭하면 액티비티가 실행되면서도 알림이 사라지지 않도록 구현하는 방법을 단계별로 살펴보겠습니다.
1단계: 새 프로젝트 생성
Android Studio에서 File → New Project 메뉴로 이동한 뒤, 필요한 항목을 모두 입력하여 새 프로젝트를 생성합니다.
2단계: 레이아웃 작성 (activity_main.xml)
res/layout/activity_main.xml 파일에 아래 코드를 추가합니다. 화면 중앙에 'Create notification' 버튼 하나를 배치하는 간단한 구성입니다.
<?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에 다음 코드를 추가합니다. 핵심은 빌더 체인에서 .setAutoCancel(false)를 호출하는 부분입니다. 이 설정 덕분에 사용자가 알림을 탭해도 알림이 자동으로 제거되지 않고 알림창에 그대로 남게 됩니다.
package app.tutorialspoint.com.notifyme;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
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 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) {
Intent notificationIntent = new Intent(MainActivity.this, MainActivity.class);
notificationIntent.addCategory(Intent.CATEGORY_LAUNCHER);
notificationIntent.setAction(Intent.ACTION_MAIN);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent resultIntent =
PendingIntent.getActivity(MainActivity.this, 0, notificationIntent, 0);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(MainActivity.this, default_notification_channel_id)
.setAutoCancel(false)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("Test")
.setContentIntent(resultIntent)
.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());
}
});
}
}
4단계: AndroidManifest.xml 확인
androidManifest.xml에 아래와 같이 MainActivity가 런처 액티비티로 등록되어 있는지 확인합니다.
<?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 아이콘을 클릭하고, 목록에서 본인의 모바일 기기를 선택하세요. 앱이 설치되면 기본 화면이 표시됩니다.
<img src="https://kr.wsxdn.com/UploadFiles_1288/202203/2022033114373242.jpg" />
버튼을 눌러 알림을 생성한 후 해당 알림을 탭하면 MainActivity가 다시 실행되지만, setAutoCancel(false) 설정 때문에 알림은 알림창에서 사라지지 않고 그대로 유지되는 것을 확인할 수 있습니다.
핵심 포인트 정리
- setAutoCancel(false): 알림을 클릭해도 자동으로 제거되지 않습니다. 반대로 true로 설정하면 클릭 시 알림이 즉시 사라집니다.
- PendingIntent: 알림 클릭 시 실행할 인텐트를 지정합니다. Android 12(API 31) 이상을 타깃으로 한다면
PendingIntent.FLAG_IMMUTABLE또는FLAG_MUTABLE플래그를 반드시 명시해야 하므로, 최신 환경에서는 네 번째 인자에 해당 플래그를 넣어주는 것이 좋습니다. - 알림 채널: Android 8.0(오레오, API 26) 이상에서는 알림을 게시하기 전에 반드시 NotificationChannel을 생성해야 합니다.