Computer >> 컴퓨터 >  >> 프로그래밍 >> Android

사용자가 클릭하면 자동으로 닫히는 Android 알림 만들기 — setAutoCancel 완벽 가이드

개요

이 튜토리얼에서는 사용자가 알림(Notification)을 탭했을 때 해당 알림이 자동으로 닫히도록 구현하는 방법을 단계별로 살펴봅니다.

핵심은 생각보다 간단합니다. NotificationCompat.Builder.setAutoCancel(true) 옵션만 추가하면 됩니다. 이 옵션이 설정되어 있으면 사용자가 알림을 클릭해 앱으로 이동하는 순간, 상태 표시줄에 있던 알림이 함께 제거됩니다. 이 옵션을 빠뜨리면 알림을 눌러도 계속 남아 있으므로 반드시 기억해 두세요.

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="알림 생성"
        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(true) 덕분에 사용자가 알림을 탭하면 자동으로 닫힙니다.

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.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) {
                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)
                        .setSmallIcon(R.drawable.ic_launcher_foreground)
                        .setContentTitle("테스트")
                        .setContentIntent(resultIntent)
                        .setAutoCancel(true) // ← 사용자가 알림을 클릭하면 자동으로 닫힘
                        .setStyle(new NotificationCompat.InboxStyle())
                        .setContentText("안녕하세요! 첫 번째 푸시 알림입니다.");

                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());
            }
        });
    }
}

참고: Android 12(API 31, S) 이상을 타깃으로 하는 앱이라면 PendingIntent 생성 시 변동성(variability) 플래그 지정이 필수입니다. 다음과 같이 PendingIntent.FLAG_IMMUTABLE(또는 FLAG_MUTABLE)을 명시적으로 전달해야 앱이 크래시되지 않습니다.

PendingIntent resultIntent = PendingIntent.getActivity(
        MainActivity.this,
        0,
        notificationIntent,
        PendingIntent.FLAG_IMMUTABLE);

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 기기가 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤 툴바의 실행(Run) 아이콘을 클릭하고, 목록에서 본인의 모바일 기기를 선택하세요. 그러면 기기에 앱의 기본 화면이 표시됩니다.

사용자가 클릭하면 자동으로 닫히는 Android 알림 만들기 — setAutoCancel 완벽 가이드

'알림 생성' 버튼을 누르면 상태 표시줄에 알림이 나타납니다. 이 알림을 탭하면 앱이 열리면서 동시에 알림이 자동으로 사라지는 것을 확인할 수 있습니다. 만약 알림이 그대로 남아 있다면 setAutoCancel(true)가 빠져 있는지 코드를 다시 점검해 보세요.