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

Android에서 특정 시간이 지난 후 알림을 자동으로 제거하는 방법

앱에서 표시한 알림(Notification)이 일정 시간이 지나면 자동으로 사라지도록 만들고 싶다면 Handler 클래스의 postDelayed() 메서드를 활용하면 됩니다. 이 글에서는 버튼을 눌러 알림을 생성한 뒤, 5초 후 해당 알림이 자동으로 제거되는 예제를 단계별로 살펴보겠습니다.

1단계 — 새 프로젝트 생성

Android Studio를 실행하고 File → New Project 메뉴로 이동한 뒤, 필요한 정보를 모두 입력하여 새 프로젝트를 생성합니다.

2단계 — 레이아웃 파일 작성 (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단계 — 메인 액티비티 구현 (src/MainActivity.java)

핵심 로직은 다음과 같습니다.

  • 버튼 클릭 시 NotificationCompat.Builder로 알림을 생성하고 notify()로 표시합니다.
  • 알림 ID를 System.currentTimeMillis() 값으로 저장해 둡니다.
  • Handler.postDelayed()를 사용해 5초(5000ms) 후 cancel(notificationId)를 호출하여 알림을 제거합니다.

또한 Android 8.0(Oreo) 이상에서는 알림 채널(Notification Channel) 생성이 필수이므로, SDK 버전을 확인한 뒤 채널을 등록하는 코드가 포함되어 있습니다.

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.Handler;
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("Test")
                                .setContentIntent(resultIntent)
                                .setStyle(new NotificationCompat.InboxStyle())
                                .setContentText("Hello! This is my first push notification");

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

                final int notificationId = (int) System.currentTimeMillis();
                assert mNotificationManager != null;
                mNotificationManager.notify(notificationId, mBuilder.build());

                // 5초 후 알림 자동 제거
                Handler h = new Handler();
                long delayInMilliseconds = 5000;
                h.postDelayed(new Runnable() {
                    public void run() {
                        mNotificationManager.cancel(notificationId);
                    }
                }, delayInMilliseconds);
            }
        });
    }
}

동작 원리 정리

여기서 가장 중요한 부분은 마지막의 Handler 코드입니다. postDelayed(Runnable, delayMillis)는 지정한 밀리초만큼 지연된 후 Runnable 내부의 코드를 실행합니다. 따라서 5000을 전달하면 알림이 표시된 지 5초 후에 mNotificationManager.cancel(notificationId)가 호출되어 상태바에서 해당 알림이 사라지게 됩니다. 지연 시간 값을 변경하면 원하는 시간만큼 조절할 수 있습니다.

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">

    <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 아이콘을 클릭하고, 목록에서 자신의 모바일 기기를 선택합니다. 앱이 실행되면 화면의 버튼을 눌러 알림을 생성한 뒤, 5초가 지난 후 알림이 자동으로 사라지는 것을 확인할 수 있습니다.